Inject JavaScript into Android WebView

Filipe Batista
Sep 29, 2015 · 2 min read

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


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

webView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
"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
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade