Monday, November 3, 2008

console.log() everywhere

I love using console.log() from Firebug. I can't imagine debugging JavaScript without it. Althought Chrome, Firefox(with Firebug) and Safari all support console.log(), IE and some other browsers do not.

Another problem is that I am too lazy to remove or comment all the console.log() in the production code (actually they are quite useful to leave around for future maintenance).

So I have written this quick snippet that basically injects the console.log() into the window object on unsupported browsers. The "virtual" window.console will appear as a removable div (click to remove) on the top rightmost corner. And the snippet would selectively turn on and off console.log() based on whether the flag ?__debug__ is appended to the end of the URL.
/*
 * Selectively turn on or off (using http://url/?__debug__ to turn on) 
 * console.log for debug.  Also create a virtual console.log() if it doesn't 
 * exist already (IE)
 */
if (/__debug__$/i.test(document.location.href)) {
  if (!window.console) {
    window.console = {};
    window.console.log = function(message) {
      
      var divId = 'v_window_console';
      var consoleDiv = document.getElementById(divId);
      
      if (!consoleDiv) {
        // create the virtual window console        
        var consoleDiv = document.createElement('div');
        consoleDiv.id = divId;
        consoleDiv.style.position = 'absolute';
        consoleDiv.style.top = '0';
        consoleDiv.style.right = '0';

        consoleDiv.onclick = function() {
          consoleDiv.innerHTML = '';
        };

        document.body.appendChild(consoleDiv);
      } 

      messageDiv = document.createElement('div');
      messageDiv.innerHTML = message;
      
      consoleDiv.appendChild(messageDiv);
    }
  }       
} else {
  // non-debug mode, an empty function
  window.console = window.console || {};
  window.console.log = function(message) {};
}

You can also link to this file which contains this snippet and all other utilities function that I collect.

2 comments:

Dean said...

greetings to all.
I would first like to thank the writers of this blog by sharing information, a few years ago I read a book called guanacaste costa rica in this book deal with questions like this one.

niz said...

Hello .. firstly I would like to send greetings to all readers. After this, I recognize the content so interesting about this article. For me personally I liked all the information. I would like to know of cases like this more often. In my personal experience I might mention a book called Generic Viagra in this book that I mentioned have very interesting topics, and also you have much to do with the main theme of this article.