如果是網頁內容裡面的alert,我們可以等網頁載入完畢,也就是在webViewDidFinishLoad中執行下面的js代碼,就可以屏蔽alert了
[myWebView stringByEvaluatingJavaScriptFromString:@"window.alert=null;"];
但上面的方法對於網頁onLoad事件裡面的alert就不起作用了
解決方案就是給UIWebView添加一個類別:
給工程添加JavaScriptAlert.h
@interface UIWebView (JavaScriptAlert) - (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame;- (BOOL)webView:(UIWebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame;@end
給工程添加JavaScriptAlert.m檔案
@implementation UIWebView (JavaScriptAlert)- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame { /* UIAlertView* dialogue = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil]; [dialogue show]; [dialogue autorelease]; */}- (BOOL)webView:(UIWebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame{ return NO;}@end
其實runJavaScriptAlertPanelWithMessage和runJavaScriptConfirmPanelWithMessage是WebUIDelegate的成員函數,詳情可以查閱WebUIDelegate的協助文檔