简体   繁体   中英

How to log errors to XCode with JavaScriptCore?

I have a project that uses JavaScriptCore to communicate between a webview and Objective C. This all works well, except I seem unable to log runtime errors to the XCode console.

I have the following:

- (void)createWebViewContext {
    //Find the context
    self.webViewContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

    //Register JS error handler
    self.webViewContext.exceptionHandler = ^(JSContext *c, JSValue *e) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"JAVASCRIPT ERROR: %@. Stack: %@", e, [e valueForProperty:@"stack"]);
        });
    };

    //Attach logger
    id logger = ^(NSString *logMessage) {
        NSLog(@"%@", logMessage);
    };
    self.webViewContext[@"console"][@"log"]   = logger;
    self.webViewContext[@"console"][@"info"]  = logger;
    self.webViewContext[@"console"][@"error"] = logger;
    self.webViewContext[@"console"][@"err"] = logger;
    self.webViewContext[@"console"][@"warn"]  = logger;
}

This code DOES seem to work - if I console.log or console.err something, I get the output in XCode. The problem is that I do NOT get errors that are thrown by JavaScript (such as SyntaxErrors, TypeErrors or similar). These kinds of errors still show up in the Safari inspector, but not in XCode.

Any way to achieve this?

Hm, try to check webViewContext.exception property, maybe this will work.

Additionally make sure that you catch all errors in window object. Like:

[self.webViewContext evaluateScript:@"window.onerror = function(msg) { console.err(msg)}"]

After that all errors should be forwarded to your console.err handler

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM