Jan 02 2009

Injecting JavaScript into a WebView

Category: Android,JavaScript,WebView examplesAleksander Kmetec @ 7:05 am

Back in early ’08, while the Androd developer challenge was in full swing, a fairly common question which went without a satisfactory answer was: “How can I manipulate the contents of a WebView?”. I now finally have the answer, thanks to a couple of lines of code I stumbled upon while looking at the source of Jeffrey Sharkey‘s OilCan.

The solution is actually very simple: wait for the original page to finish loading, then inject your own JavaScript code into it by calling webview.loadUrl(“javascript:your-code-here”) when your webvew’s onPageFinished() event is triggered. Loading an URL beginning with “javascript:” is the exact same approach used by bookmarklets.

Here’s a simple example which loads a page and then sets its text color to red:

final WebView webview = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */

/* WebViewClient must be set BEFORE calling loadUrl! */
webview.setWebViewClient(new WebViewClient() {
    public void onPageFinished(WebView view, String url)
        webview.loadUrl("javascript:(function() { " +
                "document.getElementsByTagName('body')[0].style.color = 'red'; " +


That’s it.

Please note though that alert() and confirm() JavaScript functions will not work unless you also register a WebChromeClient which implements the required methods.

Reblog this post [with Zemanta]

Tags: , , , ,

3 Responses to “Injecting JavaScript into a WebView”

  1. chris

    Hi, i really hope you can help.
    I have also a webview and a webchromeclient. but my prob is when a mp4 file is linked in a html page it does not come played??!!!
    What to do? When a mp4 file linked in a html page is opened from the standart android browser.. it just starts playing fine.

    Hope you have an answer.


  2. Aleksander Kmetec

    Unfortunately, I don’t know. But I’m sure that if you ask this question over at http://stackoverflow.com/ someone will have an answer.

  3. Marko

    Great tip, thank you!