Wednesday, August 07, 2013

IE console.log(). It works, except when it doesn't...

So I made an interesting discovery today.

console.log() in IE9 only works when the console is open!

As a web developer, and especially a JavaScript developer, the most useful tool in your arsenal is console.log(). And while you should (for the most part) remove any console.log() calls from your code as soon as you have finished debugging, sometimes your library code might contain it, or other times if you are writing a framework for an intermediary to use, you might leave a couple of messages for your intermediaries using console.log().

console.log() first made an appearance in Firefox's Firebug (or at least that is when I first noticed it) and has been in most major browsers, including Internet Explorer since version 8. Whilst developing, I have happily had my console open so I can debug things.

Anyways, fast forward to the current app I am working on. I am lucky enough to be working on a project that uses HTML5 canvas and the project I am working on is used by a game designer (who can put in some pieces of JavaScript code) so naturally, not only do I wrap certain parts in try/catch blocks, I want to let the game designer know his code snippet has failed so I do so using console.log.

On production, we were getting some weird bugs with IE9 and I could not for the life of me figure them out because every time I opened the console, lo and behold, they disappeared. This was driving me nuts!

Until today when by chance, I opened up the site in IE9 with the console closed and I got a JavaScript debugging error telling me that console was not defined?

Huh?

I opened the console to check, and it went away. I closed the console again but I still didn't see the error. Curious...

Anyways, after some googling, I found that console.log() does not work in IE if the console has not been opened.

D'oh!

Anyways, I basically got around it by creating a mock console object if the console is not present.

i.e.

if(!(window.console && console.log)) {
  console = {
    log: function(){},
    debug: function(){},
    info: function(){},
    warn: function(){},
    error: function(){}
  };
}
(credit: http://stackoverflow.com/questions/10183440/console-is-undefined-error-in-ie9)

So there you have it...

No comments: