From 7141a419860ee7f69b61b2bf5578a7f8d451a2ef Mon Sep 17 00:00:00 2001 From: Marcus Westin Date: Fri, 29 Jan 2016 12:01:46 -0500 Subject: [PATCH] Log a warning if there was an error while ObjC was retrieving messages from the javascript, instead of throwing an exception while attempting to decode the message as JSON. This can occur e.g if the webview loaded a new page immediately after dispatching a message to ObjC, in which case WebViewJavascriptBridge may not exist in the JS by the time ObjC reaches in to fetch the message queue. Fix #159, #183 --- WebViewJavascriptBridge/WKWebViewJavascriptBridge.m | 3 +++ WebViewJavascriptBridge/WebViewJavascriptBridgeBase.m | 7 ++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/WebViewJavascriptBridge/WKWebViewJavascriptBridge.m b/WebViewJavascriptBridge/WKWebViewJavascriptBridge.m index 3b0bfd61..88679fb4 100644 --- a/WebViewJavascriptBridge/WKWebViewJavascriptBridge.m +++ b/WebViewJavascriptBridge/WKWebViewJavascriptBridge.m @@ -85,6 +85,9 @@ - (void) _setupInstance:(WKWebView*)webView { - (void)WKFlushMessageQueue { [_webView evaluateJavaScript:[_base webViewJavascriptFetchQueyCommand] completionHandler:^(NSString* result, NSError* error) { + if (error != nil) { + NSLog(@"WebViewJavascriptBridge: WARNING: Error when trying to fetch data from WKWebView: %@", error); + } [_base flushMessageQueue:result]; }]; } diff --git a/WebViewJavascriptBridge/WebViewJavascriptBridgeBase.m b/WebViewJavascriptBridge/WebViewJavascriptBridgeBase.m index cfe20229..f290a48d 100755 --- a/WebViewJavascriptBridge/WebViewJavascriptBridgeBase.m +++ b/WebViewJavascriptBridge/WebViewJavascriptBridgeBase.m @@ -61,11 +61,12 @@ - (void)sendData:(id)data responseCallback:(WVJBResponseCallback)responseCallbac } - (void)flushMessageQueue:(NSString *)messageQueueString{ - id messages = [self _deserializeMessageJSON:messageQueueString]; - if (![messages isKindOfClass:[NSArray class]]) { - NSLog(@"WebViewJavascriptBridge: WARNING: Invalid %@ received: %@", [messages class], messages); + if (messageQueueString == nil || messageQueueString.length == 0) { + NSLog(@"WebViewJavascriptBridge: WARNING: ObjC got nil while fetching the message queue JSON from webview. This can happen if the WebViewJavascriptBridge JS is not currently present in the webview, e.g if the webview just loaded a new page."); return; } + + id messages = [self _deserializeMessageJSON:messageQueueString]; for (WVJBMessage* message in messages) { if (![message isKindOfClass:[WVJBMessage class]]) { NSLog(@"WebViewJavascriptBridge: WARNING: Invalid %@ received: %@", [message class], message);