For years, the world has been able to rely on Firebug and its console for debugging web sites. It has been a convenient and productive tool and we’d probably still be languishing in the window.dump() mines without it. A side-effect of this availability has made some patterns appear that don’t play nicely with consoles that aren’t implemented exactly the same way as Firebug’s console object. We’re running into a few of them now that Firefox has gained its own console object.
Here’s a not-terribly hypothetical situation you might imagine. You’re a web-developer working for a small company. You’ve got a website. You want to do some debugging on your front-end scripts. Naturally, since you have Firebug installed, the first thing you do is drop a few of these around your code:
console.log("I am here!");
Simple, effective, printf-style debugging. Then you decide you want to show your manager what you’ve done on her own computer. You point her to the address and she loads it up and says, “this is broken. I don’t have Firebug installed so I’m getting exceptions calling console.log().”
Pwnd! You throw in a check that might look like this:
if (window.console) {
// set a variable, do some stuff, maybe write
// your own log() wrapper...
Problem solved!
Maybe then, you start getting fancy and add a timer to your new logging function.
function myLogFunction(method, message) {
console.time(method.toString());
var result = method();
console.timeEnd(method.toString());
console.log(message, result);
}
Neat-O! Except, console.time() isn’t a function in some browsers and now won’t work properly.
One possibility is to check explicitly for Firebug by expanding your first window.console check like this:
if (window.console && window.console.firebug) {
That’s become a fairly standard pattern, though I believe it’ll exclude Chrome, Safari and Opera from your debugging efforts.
A better way is to test for each function you want to use:
if ("console" in window && "time" in window.console)
// define your method
This has the benefit of not coding for one particular type of debugging tool, will allow for graceful fallback in the event that your feature is not defined and allow you to tailor your debugging around different feature sets. This is the way libraries like jQuery check for browser capabilities and you should too. You want your website to work everywhere, don’t you?
An even better way around this would be to not ship your debugging code in a production web-site, but you may have good reasons to ignore this advice.