'In Android Webview, am I able to modify a webpage's DOM?

Suppose I load a 3rd party URL through webview.

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        webview = (WebView) findViewById(R.id.webview);
        webview.setWebViewClient(new HelloWebViewClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebChromeClient(new MyWebChromeClient());
        webview.loadUrl("http://ebay.com");         
    }

Is it possible for me to inject something into this WebView to replace the ebay logo with my own?



Solution 1:[1]

To expand on CommonsWare's correct answer:

WebView webview = new WebView();
webview.setWebViewClient(new WebClient());
webView.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("stackoverflow.com");

then in WebClient:

public class WebClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) 
    {       
        // Obvious next step is: document.forms[0].submit()
        view.loadUrl("javascript:document.forms[0].q.value='[android]'");       
    }
}

In a nutshell, you wait for the page to load. Then you loadUrl("javascript:[your javascript here]").

Solution 2:[2]

Not directly. You can invoke Javascript code in the context of the current Web page, via loadUrl(), much like a bookmarklet does. However, you do not have direct access to the DOM from Java code.

Solution 3:[3]

Since API level 19 there is a handy function evaluateJavascript (String script, ValueCallback<String> resultCallback) that to me makes more sense to use (but I guess the result will be the same). If you just want to run som javascript in the WebView (to modify the DOM for example) the resultCallback can be left empty.

webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient(){
    @Override
    public void onPageFinished(WebView view, String url) {
        webView.evaluateJavascript(
        "const images = document.getElementsByTagName(\"img\");\n" +
        "for(var i=0; i<images.length; i++){\n" +
        "    if(images[i].alt == \"eBay Logo\"){\n" +
        "        images[i].src = \"my_logo.png\";\n" +
        "    }\n" +
        "}", null);
    }
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://ebay.com");

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 CommonsWare
Solution 3 Marcus