Question

I am attempting to have window.onerror notify my view controller anytime it is called. I am setting a block callback on the JSContext of the web view in question and it does execute, however this only works on the initial page load in the web view. When the page is refreshed, the errors are no longer hitting the controller. Any ideas?

JSContext *ctx = [resultWebView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    ctx[@"window"][@"onerror"] = ^(JSValue *message, JSValue *file, JSValue *line) {
        NSLog(@"%@", message);
    };
Was it helpful?

Solution

The page refresh causes the JSContext to be replaced.

You need to implement a delegate for the frame load and put your window.onerror handler in your implementation of the selector for -webView:didCreateJavaScriptContext:forFrame:

@implementation MyFrameLoadDelegate

- (void)webView:(WebView *)webView didCreateJavaScriptContext:(JSContext *)context forFrame:(WebFrame *)frame
{
    context[@"window"][@"onerror"] = ^(JSValue *message, JSValue *file, JSValue *line) {
        NSLog(@"%@", message);
    };
}

@end

For a great intro to the new features recently introduced in JavaScriptCore.framework, check out the 2013 WWDC introduction "Integrating JavaScript into Native Apps" session on Apple's developer network: https://developer.apple.com/videos/wwdc/2013/?id=615

It does have a brief section towards the end on WebView.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top