Question

I am working on a Cordova based iOS project. I need to create a bit of a special plugin: first it has to be called from the iOS layer of the app, instead of starting on the JS side.

It is clear to me that normally the lifecycle of the a plugin is started in JS, then cordova.exec calls to the native layer, which instantiates the CDVPluginResult, by which then JS part is called back.

But my plugin has to have a different lifecycle. I need to start the whole thing from the iOS native part, which would call the JS layer.

How can I implement this?

Thank you for your help.

Was it helpful?

Solution 2

You can use:

[self.webView stringByEvaluatingJavaScriptFromString:@"callSomeFunction();"];

Or:

[self writeJavascript:@"doSomeJavaScript"];

If you want to work with Cordova's own event mechanism, you can call cordova.fireDocumentEvent to fire off JavaScript events (that you could attach to on the JS side):

[self writeJavascript:
  [NSString stringWithFormat:@"setTimeout( function() { cordova.fireDocumentEvent('%@_%@', {data:'%@'} ) }, 0);", 
  ID, event, data]];

If your call into JavaScript could trigger an alert or call into some other native code, it is best to wrap your JS with a setTimeout, as in the prior example.

OTHER TIPS

writeJavascript is now deprecated, you can use evalJs

[self.commandDelegate evalJs:@"console.log('foo')"];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top