diff --git a/src/content.ts b/src/content.ts index 5f7a24b..f084fdb 100644 --- a/src/content.ts +++ b/src/content.ts @@ -3,23 +3,16 @@ import { errorPage, jsonToHTML } from "./jsonformatter"; import { installCollapseEventListeners } from "./collapse"; import { safeStringEncodeNums } from "./safe-encode-numbers"; -function setJsonAsGlobalVariable(jsonObj: JSON) { +function setJsonAsGlobalVariable(this: any, jsonObj: any) { const script = document.createElement("script"); - const jsonStr = JSON.stringify(jsonObj).replace(/\\/g, "\\\\"); - script.text = `window.data=JSON.parse('${jsonStr}');`; + script.text = `Object.defineProperty(window, 'data', { value: ${JSON.stringify( + jsonObj + )}, writable: false, configurable: false });`; document.documentElement.appendChild(script); // log info message // with this queueMicrotask user can not see source file information in log - queueMicrotask(() => - console.log( - "%c%s%c%s", - "color: green; font-size: 16px;", - "JSON is exposed as variable called ", - "background-color: rgba(175, 184, 193, 0.2); font-size: 16px; margin: 0; padding: 0.2em 0.4em; border-radius: 6px", - "data" - ) - ); + queueMicrotask(() => console.log('JSON is exposed as a global variable called "data"')); } /** @@ -34,15 +27,14 @@ chrome.runtime.sendMessage({}, (response: boolean) => { // At least in chrome, the JSON is wrapped in a pre tag. const content = document.getElementsByTagName("pre")[0].textContent; let outputDoc = ""; + let jsonObj = null; if (content === null) { outputDoc = errorPage(new Error("No content"), "", document.URL); } else { try { - const jsonObj = JSON.parse(safeStringEncodeNums(content)); + jsonObj = JSON.parse(safeStringEncodeNums(content)); outputDoc = jsonToHTML(jsonObj, document.URL); - - setJsonAsGlobalVariable(jsonObj); } catch (e: any) { outputDoc = errorPage( e instanceof Error ? e : new Error(e.toString()), @@ -54,4 +46,5 @@ chrome.runtime.sendMessage({}, (response: boolean) => { document.documentElement.innerHTML = outputDoc; installCollapseEventListeners(); + setJsonAsGlobalVariable(jsonObj); }); diff --git a/src/jsonformatter.ts b/src/jsonformatter.ts index f1d1602..58c29c3 100644 --- a/src/jsonformatter.ts +++ b/src/jsonformatter.ts @@ -10,12 +10,12 @@ export function jsonToHTML(json: any, uri: string) { /** Convert a whole JSON value / JSONP response into an HTML body, without title and scripts */ function jsonToHTMLBody(json: any) { - return `