How does WebChromeClient.onJsAlert() show system dialog?

Viewed 261

If H5 show an alert in android webview, we can override WebChromeClient().onJsAlert() to show android dialog like this:

webView.setWebChromeClient(new WebChromeClient(){
    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        return super.onJsAlert(view, url, message, result);
    }

});

I would like to know where to display the dialog, and how to dismiss it in code.

1 Answers

You would simply do it in that method

  1. Create and show the AlertDialog
  2. Don't forget to call result.confirm() or result.cancel() when the dialog is dismissed in the positive or negative buttons OnClickListener respectively.
  3. Use return true to show you are handling the JS alert.

Something like this:

webView.setWebChromeClient(new WebChromeClient() {
    @Override
    public boolean onJsAlert(WebView view, final String url, String message, JsResult result) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setMessage(message)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.confirm();
                        dialog.dismiss();
                    }
                })
                .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        result.cancel();
                        dialog.dismiss();
                    }
                }).show();

        return true;
    }
});
Related