Add a script diagnostic mode to your web pages
Problem
You wish to make it easier to diagnose script related problems with your website.Solution
Begin by defining a log function that appends a div to the bottom of your page with each log message.
var isDebug = document.cookie.indexOf('debug=true')!=-1;
function log(msg) {
if (isDebug) {
var msgPane = document.getElementById('log-messages');
if (msgPane==null) {
msgPane = document.createElement('pre');
msgPane.id = 'log-messages';
document.body.appendChild(msgPane);
}
var d = document.createElement("div");
d.appendChild(document.createTextNode(msg));
msgPane.appendChild(d);
}
}
This log method only outputs each message when the value of isDebug is true. We initialise isDebug by reading a corresponding cookie. This makes our debug mode “sticky” so we can see messages related to page loads as we browse around the site.
We also need an unobtrusive means for our QA user to toggle isDebug on and off, without confronting other users with the option. Here is how to add an onkeypress handler that toggles isDebug whenever the character sequence “debug” is detected:
if (document.addEventListener) {
document.addEventListener('keypress', scanKeyPress, false);
} else if (document.attachEvent) {
document.attachEvent('onkeypress', scanKeyPress);
} else {
document.onkeypress = scanKeyPress;
}
var isIE = navigator.appName == "Microsoft Internet Explorer";
var dbgKey = "DEBUG";
var iSoFar = 0;
function scanKeyPress(keyStroke) {
var keyCode = isIE ? event.keyCode : keyStroke.which;
var keyThis = String.fromCharCode(keyCode).toUpperCase();
if (keyThis != dbgKey.charAt(iSoFar)) {
iSoFar = 0;
}
if (keyThis == dbgKey.charAt(iSoFar)) {
if (++iSoFar == dbgKey.length) {
if (isDebug) {
log('debug log disabled')
isDebug = false;
document.cookie = 'debug=; path=/';
} else {
isDebug = true;
log('debug log enabled')
document.cookie = 'debug=true; path=/';
}
}
}
};
You can try it on this page right now. Type “debug” to toggle this value:
- isDebug =
A WebTip by Dan Boresjo
