Android WebView WebChromeClient example tutorial

WebChromeClient is used to handle a JavaScript events in Android App which are produced by WebView. The examples of such events are : 
  • onCloseWindow
  • onProgressChanged
  • onJsAlert
  • onJsConfirm
  • onJsPrompt
  • onJsTimeout
In the following example, I am going to demonstrate handling of JavaScript Alert function on Android.
For more detail about WebView visit my earlier blog post on WebView.

Setting up WebView 

//initialization of webview

webView = (WebView) findViewById(;
WebSettings webSettings = webView.getSettings();

Loading HTML in WebView

Setting WebChromeClient to webView
webView.setWebChromeClient(new MyJavaScriptChromeClient());

The MyJavaScriptChromeClient class
Here we have to  override onJsAlert() method to handle JavaScript Alert Function.
private class MyJavaScriptChromeClient extends WebChromeClient {
  public boolean onJsAlert(WebView view, String url, String message,final JsResult result) {
//handle Alert event, here we are showing AlertDialog
    new AlertDialog.Builder(MainWebViewActivity.this)
       .setTitle("JavaScript Alert !")
           new AlertDialog.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                     // do your stuff
   return true;

My Html File :
testhtml.html :


  <body >

    <div onclick="alert('hello')"> Click Me !!  </div>



How it Works ?
When the text "Click Me !!" on the WebView is clicked, The android function onJsAlert(WebView view, String url, String message,final JsResult result) is called. The parameter to alert is copied to message  parameter of onJsAlert function. And rest of the handling is done there.
Here we are displaying a AlertDialog .

Enjoy..... Happy Coding....


  1. Replies
    1. just these 2 lines in your code before webview("your url")

      WebSettings webSettings = localWebView.getSettings();
      localWebView.setWebViewClient(new WebViewClient());

      i hope this will help.

  2. Once you receive an event from the web view, how do you reestablish focus on an element in the DOM of the caller? For instance, after this handler fires on the Java side, how would you handle taking any returned data (file chooser selection) and returning it to the calling HTML page?

  3. I want to hide some of the part of webpae in my webview.

    i am able to hide some part if their html have a Div id but in some case html have no div then how could i do this


Your Comment and Question will help to make this blog better...