IE friendly console.log

Internet Explorer makes me sad every time I open it to cross-browser test during development and it crashes on console.log. A simple check OR define option can kill console in the IE developer toolbar, so I decided to write a more robust cross-browser compatible console.log.

I need a shower.

var PWCC = this.PWCC || {};
PWCC.debug = true; // show logging as alerts in =<IE9

(PWCC.exe = function( window, undefined ){
  var console = window.console || {
      log : function(){log.apply( this, arguments );}
  };


  console.log( 'operates as normal' );


  function log() {
    var console = window.console,
        showLog = console || PWCC.debug, // on prod, set to PWCC.debug
        alertText = '',
        i,l;
 
    if ( showLog && ( undefined !== console ) ) {
      // console exists, log as normal
      console.log.apply( console, arguments );
    }
    else if ( showLog ) {
      // console does not exist, use alert
      for ( i=0,l=arguments.length; i<l; i++ ) {
        // show each argument on a seperate line
        alertText += arguments[i] + "rn";
      }
      // show logged items in an alert
      window.alert( alertText );
    }
  }
  PWCC.log = log;

}( this ));

By Peter Wilson

Peter has worked on the web for twenty years on everything from table based layouts in the 90s to enterprise grade CMS development. Peter’s a big fan of musical theatre and often encourages his industry colleagues to join him for a show or two in New York or in the West End.

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.