How can my iPhone Objective-C code get notified of Javascript errors in a UIWebView?

后端 未结 10 2444
再見小時候
再見小時候 2020-11-29 16:31

I need to have my iPhone Objective-C code catch Javascript errors in a UIWebView. That includes uncaught exceptions, syntax errors when loading files, undefined variable re

10条回答
  •  青春惊慌失措
    2020-11-29 16:52

    First setup WebViewJavascriptBridge , then override console.error function.

    In javascript

        window.originConsoleError = console.error;
        console.error = (msg) => {
            window.originConsoleError(msg);
            bridge.callHandler("sendConsoleLogToNative", {
                action:action,
                message:message
            }, null)
        };
    

    In Objective-C

    [self.bridge registerHandler:@"sendConsoleLogToNative" handler:^(id data, WVJBResponseCallback responseCallback) {
        NSString *action = data[@"action"];
        NSString *msg = data[@"message"];
        if (isStringValid(action)){
            if ([@"console.error" isEqualToString:action]){
                NSLog(@"JS error :%@",msg);
            }
        }
    }];
    

提交回复
热议问题