Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(bridge): Safely JSON.Stringify circular json on log #4507

Merged
merged 8 commits into from
May 6, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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