Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Javascript from @JavascriptInterface method in webView, Android?

Here is my HTML page codes:

<script>
    function native_callback() {
        alert("Test")
    }
</script>
<button onclick='native.appVersion()'>appVersion</button>

As you can see, there is only one button, and when I click the button, it will call the @JavascriptInterface method appVersion(). What I want to do is to call the javascript function native_callback() in the appVersion() method. Unfortunately, I will catch a java exception.

And Here is part of my java source codes of WebView class:

... // some other codes that not related

getSettings().setJavaScriptEnabled(true);
addJavascriptInterface(new InJavaScriptLocalObj(), "native");

... // some other codes that not related

final class InJavaScriptLocalObj {
@JavascriptInterface
    public void appVersion() {
        Log.i("JsInterface","Called!")
        loadUrl("javascript:native_callback()");
    }
}

And, I can catch the exception from web page :

Uncaught Error: Java exception was raised during method invocation -- From line 6 of http://my web page url

Line 6 is <button onclick='native.appVersion()'>appVersion</button>.

BTW, the cods Log.i("JsInterface","Called!") has been called, I can see the log.

What should I do ?

Solution Actually, it's must be called in another thread but same as your WebView object. Here is my codes:

web_view.post(new Runnable() {
        @Override
        public void run() {
            web_view.loadUrl("javascript:native_callback()");
        }
    });
like image 827
KaKa Avatar asked Feb 07 '23 00:02

KaKa


1 Answers

How about using handler ? I checked it works well in my project.

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        loadUrl("javascript:native_callback()");
    }
}, 0);
like image 200
TaeJung Shim Avatar answered Feb 10 '23 11:02

TaeJung Shim