Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

java - 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...