Inject JavaScript to Android WebView


The problem statement is when we want to load specific JavaScript on the loaded webpage within WebView in any Android Application. There are two ways to achieve the results :

 1. By using loadUrl() -> API level 18 and below

With loadUrl(), the UI will be refreshed when the script is applied and it doesn’t return any value.

webView.loadUrl("javascript:"+script);

2. By using evaluateJavascript() -> API level 19 and above
As Android Platform Version distribution shows that less than 1% devices support API level 18 and below, it will be preferable to use evaluateJavasctipt() instead of loadUrl().

webView.evaluateJavascript(script, new ValueCallback<String>() {
   	@Override
   	public void onReceiveValue(String value) {
       		/* Action to perform on callback */
   	}
});

Prerequisite :

To achieve JavaScript output, enable javascript to WebView. To do that,

webView.getSettings().setJavaScriptEnabled(true);

Points to consider

  • Apply JavaScript after finishing the loading of the Web URL. Using WebViewClient class, you can get more control of the Web Page by receiving various callbacks like onPageStarted(), onPageFinished() etc.
  • JavaScript can be applied always on UI thread so best practice to use evaluateJavascript() is inside WebViewClient class’s onPageFinished() method which indicates that page loading is finished and you can apply your JavaScript code on the UI of WebPage.

How to Use evaluateJavascript?

  1. In Activity class, initialize WebView and enable Javascript to WebView:
WebView webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);

webView.setWebViewClient(new MyWebViewClient());
webView.loadUrl("https://www.42gears.com/");
  1. Create WebViewClient class and set it to WebView using webView.setWebViewClient()
private class MyWebViewClient extends WebViewClient {

:
:
   @Override
   public void onPageFinished(WebView view, String url) {

       super.onPageFinished(view, url);

String script = "(function() { return 'JavaScript executed successfully.'; })();";

view.evaluateJavascript(script, new ValueCallback<String>() {
           @Override
           public void onReceiveValue(String value) {
Log.d("output", value); 
//prints:"JavaScript executed successfully."
           }
       });
   }
:
:
}

In addition, if you want to perform any action on a callback response of JavaScript, you can decode callback response values in JSON Format as callback values will always be in JSON format. That can be a JSON array, JSON value, JSON object.
Below code will be executed and give same output without any error :

view.evaluateJavascript(script, new ValueCallback<String>() {
   @Override
   public void onReceiveValue(String value) {
JsonReader jsonReader = new JsonReader(new StringReader(value));
       jsonReader.setLenient(true);

       try {
if(jsonReader.peek() != JsonToken.NULL && jsonReader.peek()==JsonToken.STRING) {

               String msg = jsonReader.nextString();
               if(msg != null) {
                   Log.d("output", msg);
//prints:"JavaScript executed successfully."
               }
           }
           jsonReader.close();
       } catch (IOException e) {
Log.e("Exception", "evaluateJavascript IOException : ", e);
       }

   }
});

Leave A Comment

Your email address will not be published. Required fields are marked *