Sometimes throws Uncaught Error: Error calling method on NPObject on Android

夙愿已清 提交于 2019-11-29 23:03:52

It happens when you try, using method called from javascript interface, to interact with UI. To solved it in this way:

class mJSInterface()
{

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

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

    }

}

To highlight the comment from @Leog

The same error occurs if you call the native javascript function with wrong parameters

This was the source of my error

Another reason can be a RuntimeException on a WebViewCoreThread. Any exception occurred after receiving @JavascriptInterface call will be logged as NPObject error if still running on a WebView thread. Overall insufficient trace message with little clue about the problem.

Correct your issue with handling javascript interface call on a suitable thread.

Example A. (NPObject error):

@JavascriptInterface
public void jsCall() {
    Log.v(TAG, "Prepared NullPointerException on "+Thread.currentThread());
    String s = null;
    s.length();  // This will cause NPObject error
}

Example 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();
}

Take this as an addition to @Nico.S's answer.

Operate iframe in Android 4.4 WebView may cause a similar exception(Uncaught ReferenceError: NPObject deleted), finally I find out the solution:

@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");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!