我在使用 Android 中的 Webview 时遇到问题,它是 JavascriptInterfaces。
我将一个字符串传递给 JavascriptInterface。在调试它时,我在我的 Android 应用程序中收到了正确的字符串。问题:有时我得到一个未捕获的错误:在 NPObject 上调用方法时出错。
有人知道为什么吗?
Java中的接口:
public class JSInterfaceGame extends JSInterface {
@JavascriptInterface
public void setShareText(String share){
shareText = share;
if(mJSInterfaceListener != null)
mJSInterfaceListener.onParametersChanged(SHARE_TEXT);
}
Fragment内的onCreateView-Method中的初始化:
online = (WebView) rootView.findViewById(R.id.online);
online.setWebViewClient(new WISWebviewClient() {
@Override
public void onStatusChanged(final WebView view, int progress, long duration) {
//unrelated
}
});
WebSettings ws = online.getSettings();
ws.setJavaScriptEnabled(true);
ws.setUserAgentString(USER_AGENT);
ws.setCacheMode(WebSettings.LOAD_DEFAULT);
ws.setRenderPriority(WebSettings.RenderPriority.HIGH);
SharedPreferences settings = getActivity().getSharedPreferences(GameActivity.PREFERENCES, Context.MODE_PRIVATE);
mJSInterface = new JSInterfaceGame();
mJSInterface.setJSInterfaceListener(this); // Defined elsewhere in this class.
mJSInterface.setPlayerName(settings.getString(GameActivity.PREFS_PlAYERNAME, null));
online.addJavascriptInterface(mJSInterface, "JSInterface");
online.loadUrl("http://myurl.something");
在Javascript中调用:
function makeShareText() {
var text = "Some text";
console.log(typeof text); // Always a string.
JSInterface.setShareText(text);
}