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).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…