我遇到了Android中的Webview问题,它是JavascriptInterfaces。
我将字符串传递给JavascriptInterface。调试时,我在Android应用程序中收到正确的字符串。问题:有时我得到一个Uncaught Error:在NPObject上调用错误的方法。
有人知道为什么吗?
Java中的接口:
public class JSInterfaceGame extends JSInterface {
@JavascriptInterface
public void setShareText(String share){
shareText = share;
if(mJSInterfaceListener != null)
mJSInterfaceListener.onParametersChanged(SHARE_TEXT);
}
片段中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);
}
答案 0 :(得分:35)
当您尝试使用从javascript界面调用的方法与UI进行交互时,会发生这种情况。以这种方式解决它:
class mJSInterface()
{
public void myFunction()
{
runOnUiThread(new Runnable() {
public void run() {
//Code that interact with UI
}
});
}
}
答案 1 :(得分:5)
突出@Leog
的评论如果使用错误的参数调用本机javascript函数,则会发生同样的错误
这是我的错误来源
答案 2 :(得分:3)
另一个原因可能是RuntimeException
上的WebViewCoreThread
。如果仍然在WebView线程上运行,则在收到@JavascriptInterface
调用后发生的任何异常都将记录为NPObject错误。整体跟踪消息不足,对此问题的线索很少。
通过在合适的线程上处理javascript接口调用来纠正您的问题。
示例A.(NPObject错误):
@JavascriptInterface
public void jsCall() {
Log.v(TAG, "Prepared NullPointerException on "+Thread.currentThread());
String s = null;
s.length(); // This will cause NPObject error
}
示例B.(NullPointerException):
@JavascriptInterface
public void jsCall() {
new Thread(new Runnable() {
@Override
public void run() {
Log.v(TAG, "Prepared NullPointerException on " + Thread.currentThread());
String s = null;
s.length(); // This will throw NullPointerException
}
}).start();
}
将此作为@Nico.S的答案的补充。
答案 3 :(得分:0)
在Android 4.4中运行iframe WebView可能会导致类似的异常(Uncaught ReferenceError:NPObject已删除),最后我找到了解决方案:
@Override
public void onPageFinished(final WebView view, String finishUrl) {
super.onPageFinished(view, finishUrl);
// android 4.4 may lost value of 'Android' when operating iframe
view.addJavascriptInterface(Activity.this, "Android");
}