Thursday 17 July 2014

Javascript debugging in the browser console.

When browsers first introduced console windows I was over the moon.  No longer did I have to rely on clunky alerts in order to perform simple debugging tasks.

Then came another concern.  Whilst I'm developing, or debugging an issue after release, I want to be able to access debug information without having to make any changes to a site or included scripts.  In order to do this I created a debug object that has the same methods as the console object, but can be enabled and disabled via the console.  This means that you can slap as many debug statements into your script as you like and they will never show unless you open the browser console and enable them.

Here's the code for the debug object...
// global debug object
window.debug = {};
window.debug.__defineGetter__("enabled", function () {
    return localStorage.getItem("_debug") === "true";
});
window.debug.__defineSetter__("enabled", function (value) {
    localStorage.setItem("_debug", value);
    if (value === true) {
        window.debug.dir = console.dir.bind(console);
        window.debug.error = console.error.bind(console);
        window.debug.log = console.log.bind(console);
        window.debug.warn = console.warn.bind(console);
    }
    else {
        window.debug.dir = function () { };
        window.debug.error = function () { };
        window.debug.log = function () { };
        window.debug.warn = function () { };
    }
});
window.debug.enabled = Boolean(window.debug.enabled);


In order to use it, just add debug function calls wherever you want them.  I tend to put them at the top of function calls so that I can get a step-by-step log of what was called and what parameters were passed, like this...
function AddNumbers(a, b) {
    debug.log("AddNumbers", arguments);
    return a + b;
}


If you call that with debugging disabled then it will just run as normal and log nothing.  If, however, you run it with debugging enabled then you'll get a log of what took place...


AddNumbers(2, 5)
7

debug.enabled = true
true

AddNumbers(2, 5)
AddNumbers [2, 5]
7

Once you include this in your projects, debugging is disabled by default.  Simply open the console and enable as above and it will start to show everything you've logged.

Since the enabled state of the debug object is stored in local storage, you are enabling and disabling it for that website, for that browser.  You can turn on debugging at any point in the page's life-cycle so you don't even need to reload the page in order to see debug statements that you've put in event handlers (for example).

The only other feature worth noting is the fact that I used bind to assign the console methods to the debug object.  Doing this means that the console shows the file and line number where the call to the debug object was made, and not where the debug object code is.

No comments:

Post a Comment