Zoltan Varadi
Zoltan Varadi

Reputation: 2478

iOS 7 UIWebView intercept alerts

In my app there's a UIWebView showing a web page. It sometimes displays errors in a UIAlertView that are really annoying. I would like to intercept this and show the errors in a more sophisticated way.

Is there a way where i can intercept the error message in a function and decide for myself what i want to do with it?

Thanks in advance!

Upvotes: 1

Views: 1439

Answers (1)

bogdansrc
bogdansrc

Reputation: 1344

This seems to do it:

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    JSContext *ctx = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    ctx[@"window"][@"alert"] = ^(JSValue *message) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"JavaScript Alert" message:[message toString] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    };
}

Note: only tested on iOS 8.

Upvotes: 2

Related Questions