有时抛出Uncaught Error:在Android上的NPObject上调用方法时出错

jan*_*nwo 23 android android-webview android-jsinterface

我在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);
}
Run Code Online (Sandbox Code Playgroud)

片段中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");
Run Code Online (Sandbox Code Playgroud)

在Javascript中调用:

function makeShareText() {
  var text = "Some text";
  console.log(typeof text); // Always a string.
  JSInterface.setShareText(text);
}
Run Code Online (Sandbox Code Playgroud)

Nic*_*o.S 35

当您尝试使用从javascript界面​​调用的方法与UI进行交互时,会发生这种情况.以这种方式解决它:

class mJSInterface()
{

public void myFunction()
{
    runOnUiThread(new Runnable() {

            public void run() {
                //Code that interact with UI
            }
        });

    }

}
Run Code Online (Sandbox Code Playgroud)

  • 如果使用错误的参数调用本机javascript函数,则会发生相同的错误. (4认同)
  • 我有同样的问题,但我绝对不会与用户界面进行交互. (2认同)

clo*_*jas 5

突出@Leog的评论

如果使用错误的参数调用本机javascript函数,则会发生相同的错误

这是我的错误的来源