Search code examples
javajavascriptandroidwebviewcall

How to call javascript function from java when webview page is different


I am working on an android project using HTML and webview to display.

I have

display.loadUrl("file:///android_asset/index.html");
    display.setWebViewClient(new WebViewClient() {

        public void onPageFinished(WebView view, String url)
        {
            display.loadUrl("javascript:openDialog()");
        }
    });

and this works perfectly. But the javascript function i want to call is in another page (chat.html). How do i call the javascript functions on this pages from java?


Solution

  • If you are the owner of the webpage (chat.html), you can integrate a JS-function which invokes a native method. And in this native method you can call your target-JS:

    chat.html:

    function callItNow() {
      if (typeof Android != "undefined"){ 
        if (Android.caller!= "undefined") {
          Android.caller();
        }
      }
    }
    

    in native Code, define a class:

     class MyJavascriptBridge { 
    
       public void caller() {
         //now you know you are on the right place (chat.html)
         webView.loadUrl("javascript:openDialog()"); 
       }
     }
    

    and of course you have to declare the bridge to your webview:

     webView.addJavascriptInterface(new MyJavascriptBridge(), "Android");