[英]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/我正在尝试按照此处找到的教程为 Android 开发 Cordova 插件: 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.
但是,我想知道如何从我的插件在我的 Javascript 代码中发送数据/触发事件 - 例如,当用户点击我的本机代码中的图标时,我希望我的 javascript 做一些事情。 Is this possible?
这可能吗?
So I got it to work as follows:所以我让它按如下方式工作:
I created a private CallbackContext object in my plugin:我在我的插件中创建了一个私有的 CallbackContext 对象:
private CallbackContext callbackContext;
and stored the CallbackContext supplied in the execute() method in it:并将 execute() 方法中提供的 CallbackContext 存储在其中:
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.在我的 Java 代码的其他地方,我可以访问这个回调并将插件结果发送给它。 This callback will become invalid, however, after it's first triggered, unless keepCallback is set to
true
:但是,在首次触发后,此回调将变为无效,除非 keepCallback 设置为
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!
我希望它可以帮助别人!
Yes you can trigger webview from Native code.是的,您可以从本机代码触发 webview。
For Android :对于安卓:
this.appView.loadUrl("javascript:yourmethodname());");
this.appView.loadUrl("javascript:yourmethodname());");
For iOS :对于 iOS:
[webView stringByEvaluatingJavaScriptFromString:@"yourmethodname()"];
[webView stringByEvaluatingJavaScriptFromString:@"yourmethodname()"];
yourmethodname
should be the javascript function you wish to call. yourmethodname
应该是您希望调用的 javascript 函数。
使用 Android 我实现了它:
cordova.getActivity().runOnUiThread(() -> webView.loadUrl("javascript:console.log('hey!');"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.