48

Possible Duplicate:
'console' is undefined error for internet explorer

If you have console.log statements in your code, Internet Explorer will throw a JavaScript error (at least in IE7 which is what our intranet users have installed).

I am using Firefox for most of my development testing primarily because of the functionality provided by Firebug (where I use a lot of console statements) but I also need to test in IE.

if I add the following to my JavaScript, the error does not get thrown.

var debugging = false;
if (typeof console == "undefined") 
    var console = { log: function() {} };  

The problem is that I would like to trigger an event if debugging mode is false. If I create a function to test whether debugging is false and do an action (at this point just an alert) but when I try do the following I receive an IE error saying Console is not defined.

var debugging = false; // or true   
if (typeof console == "undefined") 
    var console = { log: function() {consoleMsg()} };   

function consoleMsg() {
    if(!debugging) {
    alert('Console.log event in Production Code');
}   

If someone could help me to fix my code, provide a better way to help me achieve my goal, or direct me to a resource to edumacate myself I would be very appreciative.

Community
  • 1
  • 1
Michael BW
  • 1,070
  • 3
  • 13
  • 26

4 Answers4

139

You don't have to jump through all these hoops. Simply check if the console exists before using it.

So, instead of:

console.log('foo');

Use:

window.console && console.log('foo');

...and you won't get any errors.


Alternatively, you could just check for it at the top of your script, and if it's undefined, just fill it with an empty function:

// At the top of your script:
if ( ! window.console ) console = { log: function(){} };
// If you use other console methods, add them to the object literal above

// Then, anywhere in your script:
console.log('This message will be logged, but will not cause an error in IE7');

For a more robust solution, use this piece of code (taken from twitter's source code):

// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());
Vinícius Moraes
  • 3,506
  • 2
  • 22
  • 24
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • 3
    That'd still give a `ReferenceError` if `console` is not defined. – pimvdb Sep 28 '11 at 15:13
  • 4
    @pimvdb - forgot to add the `window.` part. Thanks. Updated. – Joseph Silber Sep 28 '11 at 15:20
  • 1
    Fixed a minor bug: Must be `window.console || (console = { log: function(){} });` instead of `window.console || console = { log: function(){} };` – some Aug 15 '12 at 09:04
  • 3
    +1 for the piece of code taken from Twitter's source code. Good spot and share (and honesty with source). – Chris Mar 24 '13 at 19:31
  • 1
    Does *NOT* work on IE - you must call typeof(console). Did you even test this on IE6/7/8? – Lilith River Jul 26 '13 at 14:47
  • @ComputerLinguist - It sure does. I just tested it in IE8. – Joseph Silber Jul 29 '13 at 00:29
  • Looks like the dev toolbar for IE will define 'console' but not 'console.log'.. – Lilith River Jul 29 '13 at 15:34
  • @ComputerLinguist - Regular users don't use the dev toolbar. If you're concerned about that, use the *more robust solution* at the bottom of my answer. That's what it's there for. – Joseph Silber Jul 29 '13 at 15:41
  • I've also gotten reports of it happening in the wild, on machines without the toolbar. Perhaps there's other javascript defining `console` but not `console.log`. – Lilith River Jul 29 '13 at 16:01
  • I'd add `typeof console[method].apply !== "function"` for the odd case in which the IE dev toolbar _is_ open - in which case console.log.apply fails (this can be an issue w/ angularjs). – roded Feb 05 '15 at 20:05
6

'console' itself needs to be a function, as well as 'log'. So:

if(typeof(console) === 'undefined') {
    console = function(){};
    console.log = function(){consoleMsg()};
}   
JDB
  • 25,172
  • 5
  • 72
  • 123
graphicdivine
  • 10,937
  • 7
  • 33
  • 59
  • 1
    Why should it be a function? I tried: `console()`, and got an error: `object 'console' is not a function` – Joseph Silber Mar 26 '12 at 04:49
  • 2
    It is an object in Firefox with firebug, Chrome, Safari and Opera. – some Aug 15 '12 at 09:11
  • Appreciate the attempt to add additional information to this answer, but it would be more appropriate to create a new answer with the suggested expanded capabilities. – JDB Dec 21 '12 at 19:10
2

Did you try try-catch:

var debugging = false; // or true 
try {  
    console.log();
} catch(ex) {
    /*var*/ console = { log: function() {consoleMsg()} };   
}
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
1
(function(debug) {
    var console;

    function wrapConsoleMethod(fnName) {
        if(fnName in console)
            console[ fnName ] = function(fn) {
                return function() {
                    if(debug)
                        return fn.apply(console, arguments);
                    else
                        alert('Console event in Production Code');
                };
            }(console[ fnName ]);
        else
            ; // fn not in console
    };

    if(!('console' in window))
        window.console = {
            log : function() {}
            // ...
        };
    console = window.console;
    wrapConsoleMethod('log');
    // ...
})(true /* debug */);

console.log('test');
Saxoier
  • 1,287
  • 1
  • 8
  • 8