9

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?

3 Answers 3

15

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!

Sign up to request clarification or add additional context in comments.

3 Comments

Fortunately the functionality I was building was already provided by the iOS plugins.
May I know how does the iOS plugin that you used send event to JS?
can you call a javascript function with the pluginResult ?
2

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.

3 Comments

This only works if calling from the CordovaActivity, the question requires calling it from a plugin.
what libraries are you importing to get this to work from a plugin?
@nomaam this is android webview
2

Using Android I achieved it with:

cordova.getActivity().runOnUiThread(() -> webView.loadUrl("javascript:console.log('hey!');"));

2 Comments

what libraries are you importing for this to work? I get a compilation error on "cordova." and "webView." cannot find symbol for both. i am running this from a plugin
The java file should be in /src/android/, then make sure that /plugin.xml is properly configured. I'd recommend to start with a plugin boilerplate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.