Safe Firebug Console in Javascript

Firebug‘s console object is an extremely useful tool for debugging and logging javascript interactions and responses, especially when working with AJAX and JSONP. What is not useful, is that when using the console object’s methods directly in your included javascript code, it will not work in most browsers other than Firefox, and of course it will cause errors if you (or your users) do not have Firebug installed.

Many of us have made the mistake of sometimes forgetting to delete our console code after testing and before launching our javascript to our production site, thus causing javascript errors, breaking the UI, or perhaps even breaking an entire application, depending on how javascript-dependent it is.

I aimed to solve this problem, and not just the problem of leaving the console code in my javascript by accident, but to allow it intentionally, if I wish, without breaking any browser that does not support it.

First Create a Utility Object to Provide a Namespace

I always find it useful to have a set of javascript utility methods that I can use in any website project. I typically contain these methods in an object literal to provide a namespace to contain them, so that they are not in the global (window) scope. I also like to use a debug parameter that I can set to true or false explicitly, or set it based on the current domain name, in order to disable any javascript code I may have written that is intended for debugging.

var U = {
    bDebug: true,
    console: function() { ... }
};

Using the New Console Function

Since the console methods are something that can be used across scripts and even across websites, it makes sense to keep access to them within a global namespace container such as this. Thus, the console methods will be accessed by using a property of the U namespace called console, which is a function, rather than an object. The console method that you wish to access is then passed as a string for the first argument. Any remaining arguments will be passed as the arguments for that method and applied to it.

U.console('log', 'This is a log test.', 'This is another log test.');

The code above will safely call console.log() and pass the second and third arguments as two arguments to that method, delimited by a space.

U.console('info', 'This is some info.');
U.console('warn', 'This is a warning.');

The two lines above will make a call to console.info(), showing the “info” icon, and to console.warn() showing the “warning” icon. Any other console methods will work in the same fashion.

Make Successive Calls to the Console With Ease

This method of making calls to the console methods is great for doing one call at time, such as showing a single line of info, logging, or displaying a warning. Making several successive calls to the console methods, however, sometimes can be irritating and looks a bit messy. For this reason, the function will also handle an object literal passed in as the first argument which contains console method names as the keys and their values as the arguments.

U.console({
    group: 'Group message',
    info: 'Display some info here.',
    dir: objectVar,
    groupEnd: null
});

The code above will make four successive calls to the console methods indicated by the key names, with the values passed as the arguments, and will be called in the order for which they are contained. If a method takes no arguments, null, false, or [] will suffice, but something must be passed in order for the object literal to validate.

Most console methods only take one argument, but for those that allow for more than one argument and you wish to take advantage of this, the object literal notation will handle this as well. Simply pass the arguments for that method in an array, rather than as one explicit value.

U.console({
    groupCollapsed: 'Group message',
    debug: 'Debug message',
    info: ['Info', 'that is', 'space delimited'],
    dir: objectVar,
    groupEnd: null
});

This code will make five consecutive calls to the console in the order for which they are contained, and will pass three arguments for the call to console.info(), which are contained in an array for the third name/value pair shown above.

The Safe Console Code

And that’s it. I think you will find that this is much more user-friendly than using the native Firebug console code in your scripts, and you can run the code only when you wish to debug, and without having to worry about breaking your application in any browsers that do not support it. This code not only ensures that the console object exists, but also ensures that the methods you are calling exist as well.

var U = {
    bDebug: true,
    /**
     * Use any console.method without throwing error if console is not present.
     * 
     * Allows you to pass in a single method as a string with the subsequent parameters being
     * that method's arguments, OR pass in an object containing keys as method names and
     * values as method arguments (single argument or array of multiple arguments).
     * 
     * @author pklauzinski
     * @param mixed m: string || object
     */
    console: function(m) {
        if (U.bDebug && typeof console === 'object' &&
                (typeof m === 'object' || typeof console[m] === 'function')) {
            var args = [];
            if (typeof m === 'object') {
                for (var sMethod in m) {
                    if (typeof console[sMethod] === 'function') {
                        args = (m[sMethod].length) ? m[sMethod] : [m[sMethod]];
                        console[sMethod].apply(console, args);
                    }
                }
            } else {
                console[m].apply(console, Array.prototype.slice.call(arguments, 1));
            }
        }
    }
};

1 comment

  1. You can also test for the console object, and if it doesn’t exist, create it with an empty log() function:

    if (typeof console === “undefined”){
    console = function(){
    this.log = function(){
    return;
    }
    }
    }

    This way you can still use console.log() any time you want, without any special wrapper functions or extra lines of code with each use. In unsupported browsers, this function simply returns. Just include this console object globally, before you call console.log() anywhere.

Leave a Reply

Your email address will not be published. Required fields are marked *