2

I understand that IE only treats console as an object if the debug window is open. If the debug window is not open, it treats console as undefined.

Which is why I decided to add an if check like this :

        if(console)
            console.log('removing child');

My understanding is that if console is undefined it will skip the console.log. However in IE8 the if(console) line passes and I get an undefined exception like before at console.log. This is weird.

Is there a way around this? and how do you code console in your code so that it runs on all three browsers?

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225

6 Answers6

9

You could add the following to the if clause:

if (console && console.log) {
    console.log('removing child');
}

Or write a log wrapper around the console.log function like this.

window.log = function () {
    if (this.console && this.console.log) {
        this.console.log(Array.prototype.slice.call(arguments));
    }
}

Use it like this:

log("This method is bulletproof", window, arguments");

And here is a jsfiddle for this: http://jsfiddle.net/joquery/4Ugvg/

Jo David
  • 1,696
  • 2
  • 18
  • 20
4

You could set console.log to an empty function

if(typeof console === "undefined") {
    console = {
        log : function () {}
    }
}

This way you have to bother only once.l

Moritz Roessler
  • 8,542
  • 26
  • 51
1

Just check if the console exists

window.console && console.log('foo');
Emil A.
  • 3,387
  • 4
  • 29
  • 46
0

Try using a condition like this instead, as if console is not supported it will throw undefined not false;

if(typeof console !== "undefined") {
console.log('removing child');
}

However to prevent having to wrap all your console log statemnts I would just put this snippet in your code. This will stop IE throwing any error

if(typeof console === "undefined") {
    console = {
        log: function() { },
        debug: function() { },
        ...
    };
}
Dominic Green
  • 10,142
  • 4
  • 30
  • 34
0

You need to check what the type of console is, and also what the type of console.log is. You might want to check this link:

What happened to console.log in IE8?

Community
  • 1
  • 1
donnywals
  • 7,241
  • 1
  • 19
  • 27
0

Check more information on the same: http://patik.com/blog/complete-cross-browser-console-log/