[英]UIWebView: Can I disable the javascript alert() inside any web page?
I am using UIWebView
to load a URL. 我正在使用
UIWebView
加载URL。
Inside the page of that URL, it uses alert("whatever msg")
as JavaScript. 在该URL的页面内,它使用
alert("whatever msg")
作为JavaScript。 My UIWebView
will pop up a window and show that alert message. 我的
UIWebView
将弹出一个窗口并显示该警报消息。
Is there a way to disable this kind of popup window or JavaScript alert window? 有没有办法禁用这种弹出窗口或JavaScript警报窗口?
在Web视图加载其内容后添加此项
[MyWebView stringByEvaluatingJavaScriptFromString:@"window.alert=null;"];
You can bind window.alert
to another function. 您可以将
window.alert
绑定到另一个函数。 So: 所以:
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.alert
to log to the console (for debugging purposes) or you can render it on the page (with a lightbox or something similar). 因此,您可以覆盖
window.alert
以登录到控制台(用于调试目的),或者您可以在页面上呈现它(使用灯箱或类似的东西)。
Since a UIWebView
translates all Javascript alerts into native UIAlertViews
it is fairly simple to block it on the native end. 由于
UIWebView
将所有Javascript警报转换为本机UIAlertViews
,因此在本机端阻止它是相当简单的。 Looking into UIAlertView.h
there is only one public method for showing an alert which is conveniently called: - (void)show;
查看
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
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.