Created
February 12, 2024 16:16
-
-
Save westc/7e071e088fe147b1ea49eb414f7f0899 to your computer and use it in GitHub Desktop.
Custom console object to allow for objects to be printed correctly in the console from within LWC by leveraging iframes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Custom console object to allow for objects to be printed correctly in the | |
* console by leveraging iframes. | |
* @type {Console} | |
*/ | |
const CONSOLE = ((realConsole) => { | |
let iframe; | |
try { | |
iframe = document.createElement('iframe'); | |
iframe.style.display = 'none'; | |
document.body.appendChild(iframe); | |
const interval = setInterval( | |
() => { | |
if (iframe.contentDocument.readyState !== 'loading') { | |
clearInterval(interval); | |
iframe.contentWindow.addEventListener('message', ({data: {consoleFuncName, consoleFuncNameArgs}}) => { | |
if (consoleFuncName && consoleFuncNameArgs) { | |
console[consoleFuncName](...consoleFuncNameArgs); | |
} | |
}); | |
} | |
}, | |
50 | |
); | |
} catch (err) {} | |
// Returns the actual console object. | |
return Object.keys(realConsole).reduce( | |
(CONSOLE, consoleFuncName) => { | |
CONSOLE[consoleFuncName] = function() { | |
try { | |
iframe.contentWindow.postMessage({consoleFuncName, consoleFuncNameArgs: [...arguments]}); | |
} | |
catch (err) { | |
realConsole[consoleFuncName](...arguments); | |
} | |
}; | |
return CONSOLE; | |
}, | |
{} | |
); | |
})(console); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment