Calling Javascript method from within webview in Android

16,426

You should execute the javascript function when the page is loaded

webView.setWebViewClient(new WebViewClient() {
    public void onPageFinished(WebView view, String url) {
        webView.loadUrl("javascript:callJS()");
    }
});

When you put onload=callJS() means that the javascript function will be call when page is load. For debugging, you can put console.log("your text here") in your javascript function and you will get it in your android studio log. (Commonly with the tag I/chromium). Otherwise, you can use Remote Debugging on Android with Chrome. The documentation here https://developer.chrome.com/devtools/docs/remote-debugging.

Share:
16,426
user462455
Author by

user462455

Updated on June 14, 2022

Comments

  • user462455
    user462455 almost 2 years

    I am trying to call a javascript method defined in a html page from within webview. Function is not being called, and I don't see any errors in the log.

    This is html file.

        </head>
        <body>
        <script type="text/javascript">
            function callJS(){
                $.ajax({url:"http://10.0.2.2:5010"});
            }
        </script>
        </body>
        </html>
    

    And this is the Java code in a Activity in android

        WebView webView = new WebView(this);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl("file:///android_asset/temp.html");
        webView.loadUrl("javascript:callJS()");
    

    Not sure how to debug this. When I add a onload=callJS() in body tag in html, I see the remote call being made. So, it looks like my HTML is fine,and it is being loaded into webview. However, webview is not able to call javascript method directly.