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?

Answers:

Answer

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

Answer

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.

Answer
WebView webview = new WebView();

//Maybe need to set to enabled javascript?
webView.getSettings().setJavaScriptEnabled(true);

webview.setWebViewClient(new WebClient());

webview.loadUrl("stackoverflow.com");

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.