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

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.

m_webview.setWebChromeClient(new JsPopupWebViewChrome());

private class JsPopupWebViewChrome extends WebChromeClient {
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder b = new AlertDialog.Builder(view.getContext())
.setTitle(view.getTitle())
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});

b.show();

// Indicate that we're handling this manually
return true;
}
}

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