Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable popups and alertboxes in android webview

I am using webview with javascript enables since it is required in my app fulltime. My issue is that I need to avoid popups while loading url's in my webview is there a way to do that?

I came across the onJsAlert() method but as per androids documentation

 Tell the client to display a javascript alert dialog.
 If the client returns true, WebView will assume that the client will handle the dialog.
 If the client returns false, it will continue execution.

and this is not what i want. I want to avoid popups and alert boxes (including prompt and confirm) any help would be appreciated

Thanks!

like image 464
user2933671 Avatar asked Apr 17 '14 16:04

user2933671


2 Answers

I tried the approach described in the accepted answer, from Kalel Wade, and by injecting JavaScript on every progress event I was able to block popups. However, I found what appears to be a much more elegant approach.

If you extend WebChromeClient, you can override its onJsAlert() method and block the built-in handler for alerts. While you're at it, you will probably want to block calls to confirm() and prompt():

WebChromeClient webChromeClient = new WebChromeClient() {
    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        result.cancel();
        return true;
    }

    @Override
    public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
        result.cancel();
        return true;
    }

    @Override
    public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
        result.cancel();
        return true;
    }
};

webView.setWebChromeClient(webChromeClient);

Given that you're seeing JavaScript alerts, I believe you must have already assigned a WebChromeClient. (If you don't do so, alerts are not supported.) So it should just be a matter of adding the overrides above.

Be sure to call result.cancel() prior to returning. From my experience, if you don't do this, the JavaScript engine seems to hang; the button stays in the pressed state, and no subsequent interaction is registered.

like image 106
Mark McClelland Avatar answered Nov 02 '22 02:11

Mark McClelland


You could try overriding alert,confirm, etc. Maybe add a flag on when to allow and when not to allow the alert to show. JavaScript: Overriding alert()

like image 4
Kalel Wade Avatar answered Nov 02 '22 01:11

Kalel Wade