Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cordova Plugin: Send event to Javascript?

I'm trying to develop a Cordova plugin for Android following the tutorial found here: http://www.mat-d.com/site/tutorial-creating-a-cordova-phonegap-plugin-for-android-app/

So far, so good. However, I'd like to know how to send data/trigger an event in my Javascript code from my plugin - for example, when a user taps an icon in my native code, I'd like my javascript to do something. Is this possible?

like image 987
opticon Avatar asked Apr 28 '15 04:04

opticon


2 Answers

So I got it to work as follows:

I created a private CallbackContext object in my plugin:

private CallbackContext callbackContext;

and stored the CallbackContext supplied in the execute() method in it:

public boolean execute(final String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    this.callbackContext = callbackContext;
}

Elsewhere in my Java code, I can access this callback and send plugin results to it. This callback will become invalid, however, after it's first triggered, unless keepCallback is set to true:

PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "WHAT");
pluginResult.setKeepCallback(true);
callbackContext.sendPluginResult(pluginResult);

This made me a happy camper. I hope it helps someone else!

like image 97
opticon Avatar answered Oct 04 '22 11:10

opticon


Yes you can trigger webview from Native code.

For Android :

this.appView.loadUrl("javascript:yourmethodname());");

For iOS :

[webView stringByEvaluatingJavaScriptFromString:@"yourmethodname()"];

yourmethodname should be the javascript function you wish to call.

like image 28
Mohammed Imran N Avatar answered Oct 04 '22 13:10

Mohammed Imran N