Skip to content

Instantly share code, notes, and snippets.

@westc
Created February 12, 2024 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save westc/7e071e088fe147b1ea49eb414f7f0899 to your computer and use it in GitHub Desktop.
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.
/**
* 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