javascript – Call JS function and write to variable

Question:

Is it possible to call a function that is in the html file that is loaded into the WebView and write the result of this function to a java variable?

Answer:

Try this:

  1. Write a custom client like this:

     final class MyWebChromeClient extends WebChromeClient { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.d("LogTag", message); result.confirm(); return true; }

    }

  2. Attach it to your WebView:

     mWebView.setWebViewClient(new HelloWebViewClient());
  3. Now load the script into the WebView:

     webView.loadUrl("javascript:alert(functionThatReturnsSomething)");
  4. Get the result in onJsAlert message.

I haven't tried it in practice, but it looks convincing. Unsubscribe if it works.

Scroll to Top