Skip to content

Instantly share code, notes, and snippets.

@jasonaden
Created October 3, 2024 18:28
Show Gist options
  • Save jasonaden/f090d8b3d28602ce6a172ead72d31d40 to your computer and use it in GitHub Desktop.
Save jasonaden/f090d8b3d28602ce6a172ead72d31d40 to your computer and use it in GitHub Desktop.
Set up external logging so we can log after `visibilitychange` event
// Open a new window
var logWindow = window.open("", "LogWindow", "width=600,height=400");
// Write initial HTML content to the new window
logWindow.document.write(`
<html>
<head>
<title>External Log Window</title>
<style>
body { font-family: monospace; background-color: #f0f0f0; padding: 10px; }
.info { color: blue; }
.warn { color: orange; }
.error { color: red; }
</style>
</head>
<body>
<pre id="log"></pre>
</body>
</html>
`);
// Create an externalConsole object with multiple methods
var externalConsole = {
log: function(message) {
this._write(message);
},
info: function(message) {
this._write(message, 'info');
},
warn: function(message) {
this._write(message, 'warn');
},
error: function(message) {
this._write(message, 'error');
},
_write: function(message, type) {
if (logWindow && !logWindow.closed) {
var logElement = logWindow.document.getElementById('log');
if (logElement) {
var formattedMessage = '';
if (typeof message === 'object') {
formattedMessage = JSON.stringify(message, null, 2);
} else {
formattedMessage = message;
}
if (type) {
formattedMessage = `<span class="${type}">${formattedMessage}</span>`;
}
logElement.innerHTML += formattedMessage + '\n';
}
} else {
console.warn('Log window is closed.');
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment