Calling Android WebView javascript from Java

Few days ago I stumbled into a javascript problem with Android WebView. I needed to call a javascript method after the a webpage had been loaded. I skimmed through the WebView documentation, but unfortunately I couldn’t find any support for javascript calling from WebView, WebViewClient or ChromeViewClient. I even found a bug in the Android bug tracker related to this, but it hadn’t been fixed yet.

Fortunately the solution turned out to be easier than I expected. In order to call WebView javascript from Java, you need to use WebView.loadUrl just as you do when you load an url. So for example if you want to call a javascript function called myTestFunction() you would write it like this:

webview.loadUrl("javascript:(function() { myTestFunction();})()");

You can call multiple functions and insert multiple lines of javascript at the same time. Remember that if you want to use alert() and confirm() functions, you need to create a WebChromeClient class that implements the onJsAlert and onJsConfirm methods.

Update 23.2.2012:

I added a blog post which explains on how to do this the other way around, i.e. how to call Java methods from a WebView. It’s available here

Update 9.8.2012:

I’ve written a tutorial which shows how to enable communication with WebView and Javascript. It contains both cases, calling javascript from application and calling application code from javascript, and it’s availabe at http://www.korri.net/tutorials/android/communication-to-and-from-android-webview-with-js.html.