如何在渲染完成之前阻止 UIWebView 中的 Javascript 警报|确认|提示? [英] How to block Javascript alert|confirm|promt in UIWebView before render completed?

查看:15
本文介绍了如何在渲染完成之前阻止 UIWebView 中的 Javascript 警报|确认|提示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 SO 的多个问题已经解决了类似的问题,但没有一个回答我的确切问题类型.大多数答案涉及运行 JS 片段并重载警报方法,如下所示:window.alert = function() {};

There are multiple questions on SO already addressing similar issues but none answers my exact type of question. Most of the answers involves running a JS snippet and overloading the alert method as such: window.alert = function() {};

我遇到的问题是加载的网页(我无法控制内容)在整个页面的呈现完成之前打开一个警报.

The problem I am having is that the webpage loaded (which I have no control over the content) opens an alert before the rendering of the whole page completes.

因此,我无法使用:- (void)webViewDidFinishLoad:(UIWebView *)webView 委托方法来运行 JS 片段.此外,在 - (void)webViewDidStartLoad:(UIWebView *)webView 中运行相同的代码段对我没有任何好处,因为它在加载 DOM 之前执行.

Because of this I cannot use the: - (void)webViewDidFinishLoad:(UIWebView *)webView delegate method to run the JS snippet. In addition running the same snippet in - (void)webViewDidStartLoad:(UIWebView *)webView won't do me any good since it executes before the DOM is loaded.

类似问题:

这方面有什么建议吗?

推荐答案

在尝试了一些有关注入 Javascript 的建议解决方案后,我回到了原生平台.

After experimenting a bit with the suggested solutions regarding injecting a Javascript I fell back on the native platform.

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

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

此方法可以很容易地在子类中或通过类别被覆盖.我最终使用了一个类别,因为 文档 提到子类化 UIAlertView 的警告.

This method can easily be either overridden in a subclass or through a category. I ended up using a category since the documentation mentions a warning for subclassing UIAlertView.

@interface UIAlertView (Blocker)
@end

#import "UIAlertView+Blocker.h"

@implementation UIAlertView (Blocker)

- (void)show {
   return;
}
@end

在包含 UIWebView 的视图控制器中导入此类别将阻止 UIAlertView 的所有实例,进而阻止所有 JS 警报.

Importing this category in the view controller that holds the UIWebView will block all instances of UIAlertView and in turn also all JS alerts.

我发现这个解决方案更强大,因为它不依赖于注入 Javascript、更改 HTML 或使用第三方库.它也与时间无关(JS-alert 代码可以在 header、body 或某些第三方库中).

I find this solution more robust since it does not rely on injecting Javascripts, changing HTML or using a third party library. It is also unrelated to timing (the JS-alert code can be in the header, body or in some third party lib).

这篇关于如何在渲染完成之前阻止 UIWebView 中的 Javascript 警报|确认|提示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆