From e4c8fe41ec3992df5c20e4d0d3b69240ce672e44 Mon Sep 17 00:00:00 2001 From: Maxim Bazuev Date: Thu, 6 May 2021 16:41:23 +0300 Subject: [PATCH] fix(bridge): Safely JSON.Stringify circular json on log (#4507) * fix: vue3 support #4506 * fix: additional JSON.stringify lines * fix: safeStringify method context --- core/native-bridge.ts | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/core/native-bridge.ts b/core/native-bridge.ts index 8d80c03324..51c69224f4 100644 --- a/core/native-bridge.ts +++ b/core/native-bridge.ts @@ -192,6 +192,15 @@ const initBridge = (w: any): void => { win.Ionic.WebView = IonicWebView; }; + const safeStringify = (value: any): string => { + const seen = new Set() + return JSON.stringify(value, (_k, v) => { + if (seen.has(v)) { return '...' } + if (typeof v === 'object') { seen.add(v) } + return v + }) + } + const initLogger = (win: WindowCapacitor, cap: CapacitorInstance) => { const BRIDGED_CONSOLE_METHODS: (keyof Console)[] = [ 'debug', @@ -271,11 +280,11 @@ const initBridge = (w: any): void => { typeof c.dir === 'function' ); }; - + const serializeConsoleMessage = (msg: any): string => { if (typeof msg === 'object') { try { - msg = JSON.stringify(msg); + msg = safeStringify(msg); } catch (e) { // ignore } @@ -362,7 +371,7 @@ const initBridge = (w: any): void => { // android platform postToNative = data => { try { - win.androidBridge.postMessage(JSON.stringify(data)); + win.androidBridge.postMessage(safeStringify(data)); } catch (e) { win?.console?.error(e); } @@ -392,7 +401,7 @@ const initBridge = (w: any): void => { url: url, line: lineNo, col: columnNo, - errorObject: JSON.stringify(err), + errorObject: safeStringify(err), }, };