How to inject javascript in android webview like chrome javascript console

If you used to inject javascript to test your website on chrome. You can do so on android webview.

To achieve it, you need to add internet permission on your AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

Then, on your main_activity_layout.xml , add webview

<WebView android:id="@+id/web"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Next, on your MainActivity.java, instance webView and add following code.

final WebView webView = (WebView)findViewById(R.id.web);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
  
  public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {     
   Log.e("browser",description);
   dialog.dismiss();
   }
 
    @Override
    public void onPageFinished(WebView view, String url) {
        // do your javascript injection here, remember "javascript:" is needed to recognize this code is javascript
        webView.loadUrl("javascript:document.write('hello')"); 
    }
     
    @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
     // this method is needed to ignore SSL certificate errors if you are visiting https website 
        handler.proceed(); 
    }
 
});
 
webView.loadUrl("https://your_sites.com");  

Javascript is disabled in default, you need to enable it by calling setJavascriptEnabled method.

Javascript needed to be added after the page is finished loaded, otherwise javascript will be debug before the page loaded.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s