I know that we can access swift function from cordova using plugin (exec).
Is there possible for swift function to call cordova javascript function ?
Regards
Yes, this it is entirely possible to call a JavaScript function from Swift, all you need is a reference to the cordova web view.
IIRC, older versions of Cordova use the UIWebView while more recent versions use the newer WKWebView. Executing JavaScript functions differs slightly depending on which web view you're using.
let webView = WKWebView(frame: view.frame)
view.addSubview(webView)
let greeting = "Your age is: "
let age = 50
// Notice the single-quotes needed to pass greeting as a string.
let javaScript = "function doSomething(a, b) { return a + b };doSomething('\(greeting)', \(age))"
webView.evaluateJavaScript(javaScript, completionHandler: { object, error in
print(object) // Prints Your age is: 50
})
Note that the WKWebView must be visible (added as a subview to a visible view) for it to execute JavaScript.
Execute arbitrary JavaScript functions using UIWebView's stringByEvaluatingJavaScript(from:). For example:
let uiWebView = UIWebView()
let greeting = "Your age is: "
let age = 50
// Notice the single-quotes needed to pass greeting as a string.
let javaScript = "function doSomething(a, b) { return a + b };doSomething('\(greeting)', \(age))"
let result = uiWebView.stringByEvaluatingJavaScriptFromString(javaScript)
print(result) // Prints Your age is: 50
The CDVPlugin type has a member called commandDelegate which is of the type CDVCommandDelegate. On there you find the function evalJs.
@objc(MyPlugin) public class MyPlugin : CDVPlugin {
override public func pluginInitialize() {
commandDelegate.evalJs("console.log('hello js')")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With