Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Webview.loadurl inside @JavascriptInterface will crashes the app

I have a webview, which is running on main thread and i am calling webview.loadurl("https://www.google.com")

its loading fine.

webview has following setting, so javascript function call some of native function.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

webView.addJavascriptInterface(this, name)

and this class has one method with @JavascriptInterface annotation

@JavascriptInterface
fun getTestData(){
**webview.loadURL("https://www.facebook.com")**
}

the bold one webview.loadURL("https://www.facebook.com") is getting crashed with following error:
java.lang.Throwable: A WebView method was called on thread ‘JavaBridge’. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 2) {95d9516} called on Looper (JavaBridge, tid 1144) {e018910}, FYI main Looper is Looper (main, tid 2) {95d9516})

I have checked for threads and webview is running on main thread, and while the control comes under the method getTestData(), the thread is javabridge.

Any help would be appreciated

>Solution :

run your code in UI thread, JS interfaces are called in some other (looks like)

@JavascriptInterface
fun getTestData(){
    Handler(Looper.getMainLooper()).post {
        webview.loadURL("https://www.facebook.com")
    }
}

from stacktrace:

All WebView methods must be called on the same thread

and you are creating WebView instance always in UI thread (as this is View, should be drawn…)

also if you are in Activity then you can use runOnUiThread{}

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading