Home > Software > Supporting no console, and partial console’s

Supporting no console, and partial console’s

January 22nd, 2009

Developing a new Javascript widget today, I am bouncing between Firefox – with Firebug and IE 6 with IE WebDeveloper V2.   I got things working nicely and have a condition in my code to check for the console object.  Handling no console has been blogged about before, here.

if( !window['console'] ) {
   window.console = { log: function(){}, warn: function(){}, error: function(){}, info: function(){}, debug: function(){} };
}


This works fine when I disable firebug, the console methods run with no result and covers IE.  Now on to Safari.  It turns out in Safari 3.1 console object is defined, but not with all the methods I typically use, specifically console.debug.  Safari 3.1 doesn’t define debug, but it does define the other methods.  To check for this I figured there could be other methods on the console I’m missing so here’s how I handle it.

function ensureConsole() {
      if( !window['console'] || console == undefined ) {
        // no console
        window.console = { log: function(){},
                    warn: function(){},
                    error: function(msg){ alert(msg); },
                    info: function(){},
                    debug: function(msg){ alert(msg); } };
      }
      if( window.console ) {
        // a partially functioning console
        var methods = ["debug", "warn", "log", "info", "error"];
        for( var i = 0, len = methods.length; i < len; ++i ) {
          var m = methods[i];
          var func = window.console[m];
          if( func == undefined || func == null ) {
            if( window.console.info ) {
              window.console[m] = window.console.info; // use info if nothing else
            }
            else {
              window.console[m] = function(){}
            }
          }
        }
      }
    }
    ensureConsole();

Now, I can safely use the console during development without too much concern over it not existing on my vistors browsers.

Software ,

  1. March 28th, 2009 at 04:11 | #1

    Thank you. Very interesting article.

  1. No trackbacks yet.
CommentLuv Enabled

Comments links could be nofollow free.