UIWebView:我可以在任何网页中禁用 javascript alert() 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3400429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 01:03:55  来源:igfitidea点击:

UIWebView: Can I disable the javascript alert() inside any web page?

javascriptiosuiwebview

提问by Hyman

I am using UIWebViewto load a URL.

我正在使用UIWebView加载 URL。

Inside the page of that URL, it uses alert("whatever msg")as JavaScript. My UIWebViewwill pop up a window and show that alert message.

在该 URL 的页面内,它alert("whatever msg")用作 JavaScript。我的UIWebView将弹出一个窗口并显示该警报消息。

Is there a way to disable this kind of popup window or JavaScript alert window?

有没有办法禁用这种弹出窗口或 JavaScript 警报窗口?

回答by pop850

Add this after your web view has loaded its content

在您的 Web 视图加载其内容后添加此内容

[MyWebView stringByEvaluatingJavaScriptFromString:@"window.alert=null;"];

回答by Vivin Paliath

You can bind window.alertto another function. So:

您可以绑定window.alert到另一个函数。所以:

window.alert = function() {
  //does nothing so effectively "disables" alert
};

Make sure you do this before you call any alerts. The neat thing about this is you can customize the way you display messages to the user. So you could override window.alertto log to the console (for debugging purposes) or you can render it on the page (with a lightbox or something similar).

请确保在调用任何警报之前执行此操作。这样做的好处是您可以自定义向用户显示消息的方式。因此,您可以覆盖window.alert以登录到控制台(用于调试目的),或者您可以在页面上呈现它(使用灯箱或类似的东西)。

回答by Tai Le Anh

Since a UIWebViewtranslates all Javascript alerts into native UIAlertViewsit is fairly simple to block it on the native end. Looking into UIAlertView.hthere is only one public method for showing an alert which is conveniently called: - (void)show;.

由于 aUIWebView将所有 Javascript 警报转换为本机UIAlertViews,因此在本机端阻止它是相当简单的。查看UIAlertView.h只有一种公共方法来显示警报,方便地称为:- (void)show;

@interface UIAlertView (Blocker)
@end

#import "UIAlertView+Blocker.h"

@implementation UIAlertView (Blocker)

- (void)show {
   return;
}
@end

You can find the answer here: https://stackoverflow.com/a/21698251/2377378

你可以在这里找到答案:https: //stackoverflow.com/a/21698251/2377378

回答by michaelxing

let script = """
                window.alert=window.confirm=window.prompt=function(n){},
                [].slice.apply(document.querySelectorAll('iframe')).forEach(function(n){if(n.contentWindow != window){n.contentWindow.alert=n.contentWindow.confirm=n.contentWindow.prompt=function(n){}}})
                """
    webView.evaluateJavaScript(script, completionHandler: nil)