Skip to content

Commit

Permalink
fix(bridge): Safely JSON.Stringify circular json on log (#4507)
Browse files Browse the repository at this point in the history
* fix: vue3 support #4506
* fix: additional JSON.stringify lines
* fix: safeStringify method context
  • Loading branch information
bazuka5801 authored May 6, 2021
1 parent 779b650 commit e4c8fe4
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions core/native-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -392,7 +401,7 @@ const initBridge = (w: any): void => {
url: url,
line: lineNo,
col: columnNo,
errorObject: JSON.stringify(err),
errorObject: safeStringify(err),
},
};

Expand Down

0 comments on commit e4c8fe4

Please sign in to comment.