【发布时间】:2017-02-15 06:56:04
【问题描述】:
我正在尝试开发一个可以将外部 JavaScript 注入 CordovaWebView 的 Cordova 插件。但我无法成功。
我在 MainActivity 中尝试了相同的方法,它扩展了 CordovaActivity 它工作正常。
这就是我所做的。
WebAppInterface 类
private class WebAppInterface {
private final Context context;
WebAppInterface(Context context) {
this.context = context;
}
@JavascriptInterface
public void showToast(String toastMsg) {
Toast.makeText(context, toastMsg, Toast.LENGTH_SHORT).show();
}
}
注入代码
WebSettings webSettings = ((WebView)appView.getEngine.getView()).getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new WebAppInterface(webView.getContext()), "android");
myWebView.loadUrl("javascript:android.showToast('Toast 1')");
来到 cordova,我制作了名为 MyPlugin 的插件,扩展了 CordovaPlugin 并覆盖了执行方法。
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if ("showLog".equals(action)) {
Log.d("showLog", "showLog");
return true;
}
if ("showToast".equals(action)) {
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
WebView webView = (WebView) UnfoldPlugin.this.webView.getEngine().getView();
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(webView.getContext()), "android");
webView.loadUrl("javascript:android.showToast('Hello World')");
}
});
return true;
}
return false;
}
我已经编写了 UnfoldPlugin.js 并调用了 cordova.exec 方法。操作“showLog”和“showToast”都被调用,但无法通过 javascript 注入成功获取 toast。
这是 Cordova 不允许通过插件进行外部 javascript 注入的问题吗?
我该如何解决这个问题?帮助。
编辑
然而 javascript:window.alert('Hello World') 有效
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if ("showToast".equals(action)) {
cordova.getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
webView.loadUrl("javascript:window.alert('Hello World')");
}
});
callbackContext.success();
return true;
}
我认为 addJavascriptInterface 不适用于 Cordova 插件。
【问题讨论】:
-
接受的答案对您有帮助吗? stackoverflow.com/questions/40974950/…
-
没有。没有帮助。
标签: android cordova android-webview cordova-plugins cordovawebview