1

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!

Zoltan Varadi
  • 2,468
  • 2
  • 34
  • 51
  • If it is an error from the `UIWebView` it should be hitting `webView:didFailLoadWithError:` before hand. You might be able to do something in here. – Popeye Oct 28 '13 at 15:26
  • The page loads perfectly, it just displays the error in an alertview. i guest it's simply using the javascript alert function. – Zoltan Varadi Oct 28 '13 at 15:28
  • Your going to have to give more information then. What you have added just isn't enough to go off. Is the error javascript related or is it that your site actually returns and error and the system is showing it. – Popeye Oct 28 '13 at 15:32
  • 1
    I'm sure this is referring to javascript:alert("Annoying message"); Zoltan, no, you can only intercept page loads and hyperlinks (WebViewDelegate shouldStartLoadWithRequest). If you have control over the web content, you can redesign the alert() javascript calls to something else that appears more sophisticated. – CSmith Oct 28 '13 at 15:35
  • Have a look at this http://stackoverflow.com/a/1585854/641062 – Vignesh Oct 28 '13 at 15:39
  • @Vignesh the answer your link leads to uses a `WebFrame` I do believe that they are OS X development only not iOS please see https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Webkit/Classes/WebFrame_Class/Reference/Reference.html so I understand why that wasn't the chosen answer. – Popeye Oct 28 '13 at 15:51
  • http://stackoverflow.com/a/9889749/792677, make sure to post the result as an answer. – A-Live Oct 28 '13 at 16:18
  • @Vignesh, i've tried that, but WebFrame is not available in iOS. – Zoltan Varadi Oct 28 '13 at 22:05
  • Sorry, @A-Live is what i meant – Zoltan Varadi Oct 28 '13 at 22:48

1 Answers1

2

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.

bogdansrc
  • 1,338
  • 2
  • 15
  • 28