Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
817 views
in Technique[技术] by (71.8m points)

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

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.

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.

Similar questions:

Any pointers on this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...