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 ));

Published by Peter Wilson

Peter Wilson is a Senior WordPress Engineer at Human Made and contributor to WordPress core. 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 theater and often encourages his WordPress community 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 *