Android: Fix title in Webview Javascript confirm() and alert() dialogs

0 Comments

Normally the alert/confirm dialog prompts have a title, but it doesn't reflect the actual title of the webpage you're viewing.

This may be somewhat annoying or confusing to your users, and thankfully it's an easy fix!

image

What you need to do is configure a custom WebChromeClient on your WebView. This allows you to tweak the styling and behaviour of the WebView components.

01.m_webview.setWebChromeClient(new JsPopupWebViewChrome());
02. 
03.private class JsPopupWebViewChrome extends WebChromeClient {
04.  @Override
05.  public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
06.    AlertDialog.Builder b = new AlertDialog.Builder(view.getContext())
07.    .setTitle(view.getTitle())
08.    .setMessage(message)
09.    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
10.      @Override
11.      public void onClick(DialogInterface dialog, int which) {
12.        result.confirm();
13.      }
14.    })
15.    .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
16.      @Override
17.      public void onClick(DialogInterface dialog, int which) {
18.        result.cancel();
19.      }
20.    });
21. 
22.    b.show();
23. 
24.    // Indicate that we're handling this manually
25.    return true;
26.  }
27.}

All of the magic happens in JsPopupWebViewChrome's onJsConfirm() method. You can apply a similar method to make this work with alert() prompts by overriding onJsAlert().

image http://24.media.tumblr.com/tumblr_ltcgdakccJ1qanfdoo1_500.jpg

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog