How to block Javascript alert|confirm|promt in UIWebView before render completed?

假如想象 提交于 2019-11-29 07:18:21

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

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;.

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

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

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).

It seems that the result may vary based on the rendering engine, there are a few ways, what seemed to work for me what this:

alert("something");
alert = function(){};
alert("awesome");

http://jsfiddle.net/g5S5M/ I know that the V8 engine that chrome uses is not the same as the one that firefox or IE use, so when making complex web applications one has to really start thinking because not all browsers interpred javascript the sameway.

One thing that you might want to look at is third party libraries that override this function, as in if you tell alert to be blank and right after another script tells it not to be blank, so ether remove that library, change the execution order or modify that library.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!