如何在渲染完成之前阻止UIWebView中的Javascript

如何在渲染完成之前阻止UIWebView中的Javascript

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

问题描述

有很多关于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.

类似的问题:





  • Capture (and prevent) alert() modal in UIWebView
  • Can I handle alert inside UIWebViewDelegate?
  • UIWebView: Can I disable the javascript alert() inside any web page?

关于此的任何指示?

推荐答案

在尝试了一些关于注入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.

我发现这个解决方案更加健壮,因为它不依赖于注入Javascripts,更改HTML或使用第三方库。它与计时无关(JS警报代码可以在标题,正文或某些第三方库中)。

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 alert | confirm | promt?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 07:40