Tech Blog

Android

Inject JavaScript to Android WebView

By Bansari Pandit2 min read
← Back to blog

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

   }
});

Keep reading

You may be interested in

Browse all articles →
Android Download file with Data URL
July 23, 20241 min read

Android Download file with Data URL

What is a Data URL? Data URLs are the type of URL scheme that is used to embed usually small types of files. In this URL, inline files are prefixed with the data: MIME type. data:[<mediatype>][;base64],<data> To download files having Data URLs inside Android: Firstly, we need to get an extension of the file from […]

By Bansari PanditRead More →
Download the file with blob URL in Android WebView
July 23, 20242 min read

Download the file with blob URL in Android WebView

What is the Blob URL? Blob URLs can only be generated by the browser with use of internal mapping and used within the current document while it’s open which means it is valid for the same session (ie. the life of the page/document). The blob URL looks like this: blob:http://example.com/550e8400-e29b-41d4-a716-446655440000 Below is the sample HTML […]

By Bansari PanditRead More →
Key Terminologies in Android Enterprise
December 20, 20227 min read

Key Terminologies in Android Enterprise

Android Enterprise is a Google-led initiative to enable the use of Android devices and applications in a workspace. This program offers APIs and tools for developers to integrate support of Android devices into the EMM (enterprise mobility management) or UEM (Unified Endpoint Management) solutions. The following are the key terms associated with Android Enterprise. This […]

By Sandeep KadamRead More →