Skip to content

Instantly share code, notes, and snippets.

@jasonbrice
Last active August 13, 2021 01:37
Show Gist options
  • Save jasonbrice/8131e38c14695afb4127 to your computer and use it in GitHub Desktop.
Save jasonbrice/8131e38c14695afb4127 to your computer and use it in GitHub Desktop.
Show console output as HTML for browsers with no console (e.g., safari on iPad)
// set an identifier for the console div
var consoleId = 'debug_console';
// initialize the debug console, dock to bottom of page
var debugConsole = function () {
var body = document.getElementsByTagName('body')[0];
// since this function also gets called on clear(),
// we'll remove the div if it exists so we can re-add it
if (document.getElementById(consoleId))
body.removeChild(document.getElementById(consoleId));
// create new div and set whatever attributes we want
var div = document.createElement('div');
div.id = consoleId;
// dock to bottom of page. styles are merely a matter of preference: move, color, change to suit.
div.setAttribute('style',
'position: fixed; bottom: 0px; left: 0px; width: 100%; height: 200px; color: #fff; background: #666; overflow: scroll;'
);
// make our new div part of the DOM
body.appendChild(div);
// add a link to call this function
var href = document.createElement('a');
href.innerHTML =
"<a href='javascript:debugConsole();' style='text-decoration: none;'>" +
"<span style='text-decoration: none; color: white;'>Clear</span></a><br/>";
div.appendChild(href);
// hook the console output
var oldf = console.log;
console.log = function () {
// use the console output for our own purposes
div.innerHTML +=
'<br/><span style="font-size: 12px; font-family: monospace;">' +
timestamp() + '.$ ' + arguments[0] + '</span>';
// also send it to the console
oldf.apply(console, arguments);
}
}
// timestamp adapted from https://gist.github.com/hurjas/2660489
var timestamp = function timeStamp() {
// Create a date object with the current time
var now = new Date();
// Create an array with the current month, day and time
var date = [now.getFullYear(), (now.getMonth() < 9 ? "0" : "") +
(now.getMonth() + 1), now.getDate()
];
// Create an array with the current hour, minute and second
var time = [now.getHours(), now.getMinutes(), now.getSeconds()];
// Determine AM or PM suffix based on the hour
var suffix = (time[0] < 12) ? "AM" : "PM";
// Convert hour from military time
time[0] = (time[0] < 12) ? time[0] : time[0] - 12;
// If hour is 0, set it to 12
time[0] = time[0] || 12;
// If seconds and minutes are less than 10, add a zero
for (var i = 1; i < 3; i++) {
if (time[i] < 10) {
time[i] = "0" + time[i];
}
}
// Return the formatted string
return date.join(".") + " " + time.join(":") + " " + suffix;
}
// initialize the console once the rest of the
// document has finished loading
window.onload = debugConsole;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment