UIWebView
does not have a method that is called when a Javascript alert is about to be shown. However you can use shouldStartLoadWithRequest:
to inform the UIWebView
about the alert and then decide whether to display it or not:
In your Javascript when you want to invoke an alert do this:
window.location.href = "alert://MESSAGE_TEXT";
In your UIWebView's delegate you can intercept that request and decide if you want to invoke the alert via javascript:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
switch (navigationType) {
case UIWebViewNavigationTypeOther:
if ([[request.URL scheme] isEqualToString:@"alert"]) {
NSString *message = [request.URL host];
if (SHOULD_SHOW_ALERT) {
// the alert should be shown
[webView stringByEvaluatingJavaScriptFromString:@"showAlert()"];
} else {
// don't show the alert
// just do nothing
}
return NO;
}
break;
default:
//ignore
}
return YES;
}
I don't know if you need to send the message text to the UIWebView
but I included it so that you can see how you can send parameters to the UIWebView. You could add more parameters in the URL's path.
Obviously you have to exchange SHOULD_SHOW_ALERT
with your own if clause that's determines whether to show the alert or not and you have to add the showAlert()
function to your Javascript.