Disable popups and alertboxes in android webview

后端 未结 2 1838
逝去的感伤
逝去的感伤 2020-12-19 08:06

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

相关标签:
2条回答
  • 2020-12-19 08:47

    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()

    0 讨论(0)
  • 2020-12-19 09:09

    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.

    0 讨论(0)
提交回复
热议问题