Inject JavaScript into Android WebView


Sometimes when you have a WebView and you are loading a page (that you don’t have control) there maybe some content that you want to remove or change the aspect.
In these situations, when you have no control over the page you are loading, inject javascript to manipulate HTML elements could be one good option. let’s see how to do it.

Assuming that you already have your WebView first of all, we must tell the WebView to enable the JavaScript execution

webview.getSettings().setJavaScriptEnabled(true);

Then we must set the WebViewClient in order to receive the onPageFinished event.

webView.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.loadUrl(
"javascript:(function() { " +
"var element = document.getElementById('hplogo');"
+ "element.parentNode.removeChild(element);" +
"})()");
}
});

On the onPageFinished event you can inject the JavaScript code that you want.

Take notice that you may watch some delay in the JavaScript execution because the code is only being executed after the page has finished loading.

Demo: removing the middle image through javascript injection
Show your support

Clapping shows how much you appreciated Filipe Batista’s story.