Firebug: avoid errors in other browsers

Posted at 6:10 pm in development, javascript

Small snippets or full-featured libraries - if you develop in Javascript and don’t have Firefox and Firebug

installed - you’d better get them now.

Firebug is a Firefox extension which brings several top-notch inspection/debugging features. You can inspect DOM, change CSS run-time and so on.

Aside DOM, CSS and Net capabilities Firebug features a very good debugger and some very useful logging capabilities. For example in your scripts you could write:

console.log ( "result is:", var );

and get the javascript variable “var” dumped into Firebug console.

Browsers Issue

Sadly, firebug as an extension is only available to Firefox. This means that any of your script will fail while running inside other browsers.

I wrote a little script to fix the problem:

if ( typeof( console) == "undefined" ) var console = {};
console.turnOff = function ()
{
	var api = [ 'log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml', 'trace', 'group', 'groupEnd', 'time', 'timeEnd', 'profile', 'profileEnd', 'count' ];
	for ( var i = 0; i < api.length; i++ ) console[ api[i] ] = function (){};
	console.firebug = "0.00";
}
if ( typeof( console.firebug) == "undefined"  ) console.turnOff();

Needless to say, I became aware afterwards a quite identical solution was available from the Firebug official site’s as well. Here’s is the official solution:

if (!window.console || !console.firebug)
{
    var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

    window.console = {};
    for (var i = 0; i < names.length; ++i)
        window.console[names[i]] = function() {}
}

The only difference is mine provides a console.turnOff() function which disables firebug logging even in firefox (when called explicitly form your script).

console.turnOff();
console.debug( 'Hello world' ); //won't output anything

 

Written by Stefano Forenza on April 19th, 2007

Leave a Reply