Having a webview in android and wanting to fiddle with the HTML?
Injecting javascript in android webview
Its easy, make sure you have javascript enabled and simply load url containing javascript:
mBrowser = new WebView(context);
mBrowser.getSettings().setJavaScriptEnabled(true);
mBrowser.loadUrl("javascript:getElementById('ad_container').style.display='none');");
In most cases, you first want to load the actual web page, then inject the javascript - this is done by using a WebViewClient which overrides onPageFinished.
mBrowser.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
// check url
if (SOME_WEBPAGE.equals(url) {
loadUrl(JAVASCRIPT_CODE);
}
}
});
mBrowser.loadUrl(SOME_WEBPAGE);
Extracting HTML from Android webview
Taking it one step further - let's get HTML from a page and use it in our program. This is accomplished by using a JavascriptInterface with our webview.
mBrowser.getSettings().setJavaScriptEnabled();
// add javascript interface with example method
mBrowser.addJavaScriptInterface(new JavaScriptInterface() {
public void setTitle(String html) {
mTitle = html;
}
}, "MY_JS");
// add webview client that calls javascript interface when page is loaded
mBrowser.addWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
view.loadUrl("javascript:window.MY_JS.setTitle(document.getElementsByTagName('title')[0].innerHTML);");
}
mBrowser.loadUrl(SOME_WEBPAGE);
That's it - using the combination of WebVievClient and JavascriptInterface is very powerful - drawback is that I have not found an easy way of debugging javascript - if your javascript fails it will fail silent.
Nice thing is you can test your javascript on Firefox using Firebug on your main computer before adding code to your android project.