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

你。 提交于 2019-12-24 22:01:26

问题


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?


回答1:


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");



回答2:


suppose you'r function in javascript is hello.

webview.loadUrl("javascript:hello();");

I think that'll do it.



来源:https://stackoverflow.com/questions/21665724/how-to-call-javascript-function-from-java-when-webview-page-is-different

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