JavaScript alert dialogs in WebView - How to make them work
suggest changeBy default, WebView does not implement JavaScript alert dialogs, i.e. alert() will do nothing. To make them work, first enable JavaScript, then set a WebChromeClient that shows the dialog. WebChromeClient.onJsAlert returns false and shows nothing, so the override has to display the dialog itself and call JsResult.confirm() or JsResult.cancel(). Returning true without one of those calls leaves the JavaScript side waiting.
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(view.getContext())
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
result.cancel();
}
})
.show();
return true;
}
});
The message and URL are available in onJsAlert if you want a custom dialog or a log line.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents