Using UIWebView to mask alert warning box in iOS development

  • 2021-07-06 11:55:18
  • OfStack

If it is alert in the web page content, we can wait for the web page to load, that is, execute the following js code in webViewDidFinishLoad, and then we can shield alert


[myWebView stringByEvaluatingJavaScriptFromString:@"window.alert=null;"];

However, the above method does not work for alert in the onLoad event of the web page

The solution is to add a category to UIWebView:

Add JavaScriptAlert. h to the project


@interface UIWebView (JavaScriptAlert) 
- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame;
- (BOOL)webView:(UIWebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame;
@end

Add the JavaScriptAlert. m file to the project


@implementation UIWebView (JavaScriptAlert)
- (void)webView:(UIWebView *)sender runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame {
/*
UIAlertView* dialogue = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:@" Good " otherButtonTitles:nil];
[dialogue show];
[dialogue autorelease];
*/
}
- (BOOL)webView:(UIWebView *)sender runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WebFrame *)frame{
return NO;
}
@end

Actually runJavaScriptAlertPanelWithMessage and runJavaScriptConfirmPanelWithMessage are member functions of WebUIDelegate. For details, please refer to the help document of WebUIDelegate.


Related articles: