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

TIMEX picture TIMEX · Feb 8, 2010 · Viewed 28.4k times · Source

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?

Answer

Carlos Rendon picture Carlos Rendon · Feb 16, 2011

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]").