Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access javascript function cordova from swift?

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

like image 394
Adrian Avatar asked Jun 07 '26 03:06

Adrian


2 Answers

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.

WKWebView

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.

UIWebView

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
like image 50
paulvs Avatar answered Jun 09 '26 06:06

paulvs


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')")
  }
}
like image 27
NtFreX Avatar answered Jun 09 '26 07:06

NtFreX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!