380

I'm using Firebug and have some statements like:

console.log("...");

in my page. In IE8 (probably earlier versions too) I get script errors saying 'console' is undefined. I tried putting this at the top of my page:

<script type="text/javascript">
    if (!console) console = {log: function() {}};
</script>

still I get the errors. Any way to get rid of the errors?

Sebastian Zartner
  • 16,477
  • 8
  • 74
  • 116
user246114
  • 45,805
  • 40
  • 106
  • 145
  • 4
    Use `typeof` in your if, it will avoid undefined errors: `if(typeof console === "undefined") { var console = { log: function (logMsg) { } }; }` – Flak DiNenno Feb 04 '13 at 23:19
  • 21
    console.log() only works when IE's dev tool is open (yes IE is crappy). see http://stackoverflow.com/questions/7742781/why-javascript-only-works-after-opening-developer-tools-in-ie-once – Adrien Be Jul 16 '13 at 13:14
  • 1
    Best answer to that question is http://stackoverflow.com/a/16916941/2274855 – Vinícius Moraes Nov 19 '13 at 15:05
  • 1
    see https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js – Aprillion Nov 27 '13 at 15:54
  • 1
    @Aprillion link is broken, use this one instead: https://github.com/h5bp/html5-boilerplate/blob/master/src/js/plugins.js – Alfred Bez Oct 22 '15 at 07:27
  • Using console logging in production is a bad idea anyway, at least a code smell. You might, by accident, expose sensitive user data. I use Sonar to detect any `console.log` statements, and force me to remove it before moving to production. – Justus Romijn Nov 16 '15 at 10:36
  • 1
    `if(!window.console) alert("Please use a real browser")` – JCOC611 Jan 29 '16 at 18:28

21 Answers21

379

Try

if (!window.console) console = ...

An undefined variable cannot be referred directly. However, all global variables are attributes of the same name of the global context (window in case of browsers), and accessing an undefined attribute is fine.

Or use if (typeof console === 'undefined') console = ... if you want to avoid the magic variable window, see @Tim Down's answer.

Community
  • 1
  • 1
kennytm
  • 469,458
  • 94
  • 1,022
  • 977
  • 161
    Just to be clear to anyone else using this, place `` at the top of your page! Thanks Kenny. – windowsgm Jul 03 '12 at 15:41
  • 11
    What about `var console = console || { log: function() {} };` – devlord Oct 31 '12 at 03:08
  • 9
    @lorddev To use that shorthand you need to include `window`: `var console = window.console || { log: function() {} };` – jlengstorf Jan 22 '13 at 21:51
  • 64
    Damn... you build a nice website, developing it for your favorite browser. At the end you spend 4-5 HOURS making it compatible with all other MODERN browsers, and then you spend 4-5 DAYS making it compatible with IE. – Israel May 28 '13 at 19:43
  • 6
    The problem with that answer is if you are using another name like debug, warn, count with browser that lack console will throw a exception see the better way to do that http://stackoverflow.com/a/16916941/2274855 – Vinícius Moraes Jun 04 '13 at 11:45
  • 4
    Just FYI, the code above posted by killianmcc simply prevents an error, but the actual `console.log()` function does absolutely nothing. – Alex W Sep 09 '13 at 14:32
  • @lorddev that will only affect the local scope of console. You need to modify `window.log` to affect other script files, which fall outside the local scope. – Petrus Theron Dec 29 '13 at 13:44
  • Ugh! I would just like to say that this will only work if you own the page in question and can modify it. This does not help if your code is in an embedded control in a 3rd party app you don't control that is starting an unknown browser beyond your control. – Michael Dec 07 '20 at 22:40
321

Paste the following at the top of your JavaScript (before using the console):

/**
 * Protect window.console method calls, e.g. console is not defined on IE
 * unless dev tools are open, and IE doesn't define console.debug
 * 
 * Chrome 41.0.2272.118: debug,error,info,log,warn,dir,dirxml,table,trace,assert,count,markTimeline,profile,profileEnd,time,timeEnd,timeStamp,timeline,timelineEnd,group,groupCollapsed,groupEnd,clear
 * Firefox 37.0.1: log,info,warn,error,exception,debug,table,trace,dir,group,groupCollapsed,groupEnd,time,timeEnd,profile,profileEnd,assert,count
 * Internet Explorer 11: select,log,info,warn,error,debug,assert,time,timeEnd,timeStamp,group,groupCollapsed,groupEnd,trace,clear,dir,dirxml,count,countReset,cd
 * Safari 6.2.4: debug,error,log,info,warn,clear,dir,dirxml,table,trace,assert,count,profile,profileEnd,time,timeEnd,timeStamp,group,groupCollapsed,groupEnd
 * Opera 28.0.1750.48: debug,error,info,log,warn,dir,dirxml,table,trace,assert,count,markTimeline,profile,profileEnd,time,timeEnd,timeStamp,timeline,timelineEnd,group,groupCollapsed,groupEnd,clear
 */
(function() {
  // Union of Chrome, Firefox, IE, Opera, and Safari console methods
  var methods = ["assert", "cd", "clear", "count", "countReset",
    "debug", "dir", "dirxml", "error", "exception", "group", "groupCollapsed",
    "groupEnd", "info", "log", "markTimeline", "profile", "profileEnd",
    "select", "table", "time", "timeEnd", "timeStamp", "timeline",
    "timelineEnd", "trace", "warn"];
  var length = methods.length;
  var console = (window.console = window.console || {});
  var method;
  var noop = function() {};
  while (length--) {
    method = methods[length];
    // define undefined methods as noops to prevent errors
    if (!console[method])
      console[method] = noop;
  }
})();

The function closure wrapper is to scope the variables as to not define any variables. This guards against both undefined console and undefined console.debug (and other missing methods).

EDIT: I noticed that HTML5 Boilerplate uses similar code in its js/plugins.js file, if you're looking for a solution that will (probably) be kept up-to-date.

Peter Tseng
  • 11,991
  • 3
  • 64
  • 53
  • 14
    Why has this answer so few upvotes? It is the most complete one of the ones posted here. – mavilein Apr 03 '13 at 18:44
  • Because of date. Absolutely agree with correct working solutions. I think this topic need be moderated. Sorry for bad English. – woto Apr 07 '13 at 00:42
  • Quite complete except that it will not try to redirect logging to the log function (if present) so all logs are lost – Christophe Roussy May 24 '13 at 15:06
  • To clarify, for example, if console.debug is undefined, redirect it to console.log instead of noop? – Peter Tseng May 25 '13 at 03:36
  • 5
    When would this occur exactly? This code should only define elements that are not defined yet. – Peter Tseng Aug 20 '13 at 20:49
  • @honyovk that is not correct. This code doesn't override any existing methods. Instead it stubs any non-existent method on the current console implementation to do nothing when called. For example, if Firefox had a method `console.highfive()`, and Chrome didn't, this code would define `console.highfive = function() {};` so calling `console.highfive(user);` in Chrome would do nothing but would still execute as intended in Firefox. In IE, each method would be stubbed. – John Kary Nov 21 '13 at 22:24
  • Also see similar solution called "firebugx.js" located here: http://code.google.com/p/fbug/source/browse/branches/firebug1.2/lite/firebugx.js?r=187 – Roberto Mar 11 '14 at 19:30
  • Last line should be: }()); – stefgosselin May 09 '15 at 17:32
  • 4
    I think either way - (function(){...}()) or (function(){...})() - works actually – Peter Tseng May 11 '15 at 04:13
74

Another alternative is the typeof operator:

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

Yet another alternative is to use a logging library, such as my own log4javascript.

Tim Down
  • 292,637
  • 67
  • 429
  • 506
  • It would be a good idea to change undeclared assignment into a proper declaration, though. – kangax Jul 24 '10 at 22:41
  • 1
    Do you mean using `var`? That would only confuse things here. Or do you mean assigning to `window.console` rather than `console`? – Tim Down Jul 24 '10 at 23:18
  • Using `var`. Why would it confuse things here? – kangax Jul 24 '10 at 23:22
  • Putting a `var` inside an `if` block is confusing and looks like a mistake. It also changes the nature of `console` regardless of whether the `if` block is executed because a variable is always declared. I agree that implicitly assigning to a global variable as I am here also looks like a mistake, but it only changes behaviour when `console` is undefined. Neither is ideal. – Tim Down Jul 25 '10 at 00:07
  • The problem with omitting `var` when assigning to `console` — as in this example — is not even so much that it looks like a mistake. First of all, IE DOM has an unfortunate peculiarity when undeclared assignment throws error if identifier is the same as id of one of the elements in the document. Second — and more importantly — in ES5 strict mode, undecl. assignment is actually a deliberate ReferenceError. Given that strict mode is more or less a future direction of a language, for compatibility reasons, undecl. assignments are best avoided. But if you must, `this.console=..` is an alt. option. – kangax Jul 25 '10 at 00:29
  • Re the IE DOM global scope pollution insanity, I am aware of it but we already know console is undefined, at least at the point that code is run. The ES5 point is a good one: I haven't started thinking in terms of ES5 all the time yet. For myself, I wouldn't consider using that code anyway and instead create a wrapper around console. – Tim Down Jul 25 '10 at 17:12
  • Hey Tim. I see you changed `console = ...` to `this.console = ...`. Excellent, I changed my vote. – kangax Jul 26 '10 at 15:04
  • Ah, right, thanks. Wondered whether it might've been you. I was waiting till we'd finished discussing before changing it; the ES5 point had clinched it, but I wasn't sure if you were still advocating `var console` over `this.console`. – Tim Down Jul 26 '10 at 15:15
  • Well I personally use `var console = ...` and `this.console = ...` interchangeably. Let me also point out that variable declaration does not change the nature of existing variable (or property of variable object, to be precise). If `console` is already a global property, `var console` executed in global code is essentially a no-op. That's why `if (typeof console == 'undefined') { var console = ... }` does not change `console` at all if it's already declared. Alternative version would be `var console; if (typeof console == 'undefined') { console = .. }`, but this could look confusing as well :) – kangax Jul 26 '10 at 15:27
  • OK. You're right. Obviously using `var console` would change the nature of a `console` property that was added to the global object later on, but that wasn't the point we were previously discussing. Thanks. – Tim Down Jul 26 '10 at 15:46
  • 2
    What a confusing discussion. +1 to orginal answer. If I could give +2 I would for providing a link to you own log4javascript. Thanks OP! – Jay Taylor Jul 03 '11 at 16:07
  • Unexpected 'typeof'. Use '===' to compare directly with undefined. – yckart Sep 06 '12 at 23:36
  • 8
    @yckart: No. `typeof` is guaranteed to return a string and `"undefined"` is a string. When the two operands are of the same type, `==` and `===` are specified to perform exactly the same steps. Using `typeof x == "undefined"` is a rock-solid way to test whether `x` is undefined in any scope and any ECMAScript 3 compliant environment. – Tim Down Sep 07 '12 at 12:08
  • Also to be strict this should use ===. This is the only 100% strict answer supplied just saying !window.console will throw errors in some browsers. if (typeof(var) === "undefined") and use braces is the correct strict syntax for this operation. – Hugh Wood Feb 12 '13 at 17:19
  • @HughWood: `==` and `===` are precisely equivalent in this case because both operands are guaranteed to be strings, so there's no objective advantage to using `===`. Also `typeof` is an operator rather than a function so parentheses are unnecessary. – Tim Down Feb 12 '13 at 17:31
  • @TimDown Sorry I wasn't clear, the code isn't strict, === will make it strict and pass linting, hope that clarifies what I meant – Hugh Wood Feb 12 '13 at 17:47
  • @HughWood: Fair enough, if "strict" means "conforms to Douglas Crockford's subjective idea of good practice". Standardizing on `===` is not a bad idea, but neither is using `==` where appropriate. As you may have guessed, I find JSLint excessively opinionated. – Tim Down Feb 12 '13 at 17:56
  • @TimDown I think that Crockford is right this time round, but I would still like to check this vs browser interpreters on any real world differences, but this is a different thread. – Hugh Wood Feb 12 '13 at 19:21
  • @HughWood: Well, in the ECMAScript spec, the steps for `==` and `===` are precisely the same when the operands are of the same type, and no benchmark I've seen has shown any significant performance differences between them for such cases. – Tim Down Feb 13 '13 at 00:56
47

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,381
  • 2
  • 20
  • 24
13

In my scripts, I either use the shorthand:

window.console && console.log(...) // only log if the function exists

or, if it's not possible or feasible to edit every console.log line, I create a fake console:

// check to see if console exists. If not, create an empty object for it,
// then create and empty logging function which does nothing. 
//
// REMEMBER: put this before any other console.log calls
!window.console && (window.console = {} && window.console.log = function () {});
iblamefish
  • 4,401
  • 3
  • 28
  • 43
10

You can use console.log() if you have Developer Tools in IE8 opened and also you can use the Console textbox on script tab.

  • 7
    This is not good if you forget to sweap the code of console. The error in IE8 will prevent your JS code from working – yunzen Aug 30 '12 at 09:26
7
if (typeof console == "undefined") {
  this.console = {
    log: function() {},
    info: function() {},
    error: function() {},
    warn: function() {}
  };
}
Kehan
  • 147
  • 2
  • 6
insign
  • 3,407
  • 30
  • 29
  • 1
    caveat emptor: this should be defined at the global level where `this` refers to `window`. – Sgnl Dec 22 '17 at 11:13
7

Based on two previous answers by

and the documentations for

Here's a best effort implementation for the issue, meaning if there's a console.log which actually exists, it fills in the gaps for non-existing methods via console.log.

For example for IE6/7 you can replace logging with alert (stupid but works) and then include the below monster (I called it console.js): [Feel free to remove comments as you see fit, I left them in for reference, a minimizer can tackle them]:

<!--[if lte IE 7]>
<SCRIPT LANGUAGE="javascript">
    (window.console = window.console || {}).log = function() { return window.alert.apply(window, arguments); };
</SCRIPT>
<![endif]-->
<script type="text/javascript" src="console.js"></script>

and console.js:

    /**
     * Protect window.console method calls, e.g. console is not defined on IE
     * unless dev tools are open, and IE doesn't define console.debug
     */
    (function() {
        var console = (window.console = window.console || {});
        var noop = function () {};
        var log = console.log || noop;
        var start = function(name) { return function(param) { log("Start " + name + ": " + param); } };
        var end = function(name) { return function(param) { log("End " + name + ": " + param); } };

        var methods = {
            // Internet Explorer (IE 10): http://msdn.microsoft.com/en-us/library/ie/hh772169(v=vs.85).aspx#methods
            // assert(test, message, optionalParams), clear(), count(countTitle), debug(message, optionalParams), dir(value, optionalParams), dirxml(value), error(message, optionalParams), group(groupTitle), groupCollapsed(groupTitle), groupEnd([groupTitle]), info(message, optionalParams), log(message, optionalParams), msIsIndependentlyComposed(oElementNode), profile(reportName), profileEnd(), time(timerName), timeEnd(timerName), trace(), warn(message, optionalParams)
            // "assert", "clear", "count", "debug", "dir", "dirxml", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "msIsIndependentlyComposed", "profile", "profileEnd", "time", "timeEnd", "trace", "warn"

            // Safari (2012. 07. 23.): https://developer.apple.com/library/safari/#documentation/AppleApplications/Conceptual/Safari_Developer_Guide/DebuggingYourWebsite/DebuggingYourWebsite.html#//apple_ref/doc/uid/TP40007874-CH8-SW20
            // assert(expression, message-object), count([title]), debug([message-object]), dir(object), dirxml(node), error(message-object), group(message-object), groupEnd(), info(message-object), log(message-object), profile([title]), profileEnd([title]), time(name), markTimeline("string"), trace(), warn(message-object)
            // "assert", "count", "debug", "dir", "dirxml", "error", "group", "groupEnd", "info", "log", "profile", "profileEnd", "time", "markTimeline", "trace", "warn"

            // Firefox (2013. 05. 20.): https://developer.mozilla.org/en-US/docs/Web/API/console
            // debug(obj1 [, obj2, ..., objN]), debug(msg [, subst1, ..., substN]), dir(object), error(obj1 [, obj2, ..., objN]), error(msg [, subst1, ..., substN]), group(), groupCollapsed(), groupEnd(), info(obj1 [, obj2, ..., objN]), info(msg [, subst1, ..., substN]), log(obj1 [, obj2, ..., objN]), log(msg [, subst1, ..., substN]), time(timerName), timeEnd(timerName), trace(), warn(obj1 [, obj2, ..., objN]), warn(msg [, subst1, ..., substN])
            // "debug", "dir", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "time", "timeEnd", "trace", "warn"

            // Chrome (2013. 01. 25.): https://developers.google.com/chrome-developer-tools/docs/console-api
            // assert(expression, object), clear(), count(label), debug(object [, object, ...]), dir(object), dirxml(object), error(object [, object, ...]), group(object[, object, ...]), groupCollapsed(object[, object, ...]), groupEnd(), info(object [, object, ...]), log(object [, object, ...]), profile([label]), profileEnd(), time(label), timeEnd(label), timeStamp([label]), trace(), warn(object [, object, ...])
            // "assert", "clear", "count", "debug", "dir", "dirxml", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "profile", "profileEnd", "time", "timeEnd", "timeStamp", "trace", "warn"
            // Chrome (2012. 10. 04.): https://developers.google.com/web-toolkit/speedtracer/logging-api
            // markTimeline(String)
            // "markTimeline"

            assert: noop, clear: noop, trace: noop, count: noop, timeStamp: noop, msIsIndependentlyComposed: noop,
            debug: log, info: log, log: log, warn: log, error: log,
            dir: log, dirxml: log, markTimeline: log,
            group: start('group'), groupCollapsed: start('groupCollapsed'), groupEnd: end('group'),
            profile: start('profile'), profileEnd: end('profile'),
            time: start('time'), timeEnd: end('time')
        };

        for (var method in methods) {
            if ( methods.hasOwnProperty(method) && !(method in console) ) { // define undefined methods as best-effort methods
                console[method] = methods[method];
            }
        }
    })();
Community
  • 1
  • 1
TWiStErRob
  • 38,918
  • 20
  • 146
  • 220
  • I'm not sure if we need `methods.hasOwnProperty(method) && ` in the for loop. – TWiStErRob Jul 24 '13 at 00:13
  • I'm sure that you do need it. – ErikE Oct 07 '13 at 22:12
  • Did a quick test in Chrome's console: `> x = { a: 1, b: 2}` --> `Object {a: 1, b: 2}` and `for(var f in x) {console.log(f + " " + x[f]);} 'end'` --> `a 1 b 2 "end"`. So a created anonymous object does not have any additional property, and `methods` is just created before the `for` loop. Is it possible to hack the above? – TWiStErRob Oct 08 '13 at 17:26
  • 3
    Yes. `var x = { a: 1, b: 2}; Object.prototype.surprise = 'I\'m in yer objectz'; for (var f in x) {console.log(f, x[f]);}` You never know what a library has done to the objects in the inheritance chain of the object you're working with. Thus the recommendation by javascript code quality tools like jshint and jslint to use `hasOwnProperty`. – ErikE Oct 09 '13 at 02:52
6

In IE9, if console is not opened, this code:

alert(typeof console);

will show "object", but this code

alert(typeof console.log);

will throw TypeError exception, but not return undefined value;

So, guaranteed version of code will look similar to this:

try {
    if (window.console && window.console.log) {
        my_console_log = window.console.log;
    }
} catch (e) {
    my_console_log = function() {};
}
bonbonez
  • 5,818
  • 2
  • 13
  • 16
6

I am only using console.log in my code. So I include a very short 2 liner

var console = console || {};
console.log = console.log || function(){};
Ruben Decrop
  • 1,561
  • 1
  • 14
  • 9
  • 1
    How its working.. .I'm not seeing any console.log line printed to the IE browser, i have tested with 2 different systems where in 1 - console.log is working and 2 system its not. i tried in both but not able to see any log in both the systems . – kiran Sep 13 '16 at 00:46
2

Noticed that OP is using Firebug with IE, so assume it's Firebug Lite. This is a funky situation as console gets defined in IE when the debugger window is opened, but what happens when Firebug is already running? Not sure, but perhaps the "firebugx.js" method might be a good way to test in this situation:

source:

https://code.google.com/p/fbug/source/browse/branches/firebug1.2/lite/firebugx.js?r=187

    if (!window.console || !console.firebug) {
        var names = [
            "log", "debug", "info", "warn", "error", "assert",
            "dir","dirxml","group","groupEnd","time","timeEnd",
            "count","trace","profile","profileEnd"
        ];
        window.console = {};
        for (var i = 0; i < names.length; ++i)
            window.console[names[i]] = function() {}
    }

(updated links 12/2014)

Roberto
  • 3,420
  • 1
  • 17
  • 20
1

For debugging in IE, check out this log4javascript

Praveen
  • 50,562
  • 29
  • 125
  • 152
1

For IE8 or console support limited to console.log (no debug, trace, ...) you can do the following:

  • If console OR console.log undefined: Create dummy functions for console functions (trace, debug, log, ...)

    window.console = { debug : function() {}, ...};

  • Else if console.log is defined (IE8) AND console.debug (any other) is not defined: redirect all logging functions to console.log, this allows to keep those logs !

    window.console = { debug : window.console.log, ...};

Not sure about the assert support in various IE versions, but any suggestions are welcome. Also posted this answer here: How can I use console logging in Internet Explorer?

Community
  • 1
  • 1
Christophe Roussy
  • 13,732
  • 2
  • 75
  • 75
1
console = console || { 
    debug: function(){}, 
    log: function(){}
    ...
}
David Glass
  • 2,639
  • 3
  • 14
  • 23
1

Stub of console in TypeScript:

if (!window.console) {
console = {
    assert: () => { },
    clear: () => { },
    count: () => { },
    debug: () => { },
    dir: () => { },
    dirxml: () => { },
    error: () => { },
    group: () => { },
    groupCollapsed: () => { },
    groupEnd: () => { },
    info: () => { },
    log: () => { },
    msIsIndependentlyComposed: (e: Element) => false,
    profile: () => { },
    profileEnd: () => { },
    select: () => { },
    time: () => { },
    timeEnd: () => { },
    trace: () => { },
    warn: () => { },
    }
};
gdbdable
  • 4,065
  • 3
  • 27
  • 42
1

I'm using fauxconsole; I modified the css a bit so that it looks nicer but works very well.

Stijn Geukens
  • 14,803
  • 7
  • 60
  • 100
0

You can use the below to give an extra degree of insurance that you've got all bases covered. Using typeof first will avoid any undefined errors. Using === will also ensure that the name of the type is actually the string "undefined". Finally, you'll want to add a parameter to the function signature (I chose logMsg arbitrarily) to ensure consistency, since you do pass whatever you want printed to the console to the log function. This also keep you intellisense accurate and avoids any warnings/errors in your JS aware IDE.

if(!window.console || typeof console === "undefined") {
  var console = { log: function (logMsg) { } };
}
Flak DiNenno
  • 1,941
  • 2
  • 25
  • 52
0

Sometimes console will work in IE8/9 but fail at other times. This erratic behaviour depends on whether you have developer tools open and is described in stackoverflow question Does IE9 support console.log, and is it a real function?

Community
  • 1
  • 1
Anon
  • 4,044
  • 2
  • 26
  • 46
0

Encountered similar problem running console.log in child windows in IE9, created by window.open function.

It seems that in this case console is defined only in parent window and is undefined in child windows until you refresh them. Same applies to children of child windows.

I deal with this issue by wrapping log in next function (below is fragment of module)

getConsole: function()
    {
        if (typeof console !== 'undefined') return console;

        var searchDepthMax = 5,
            searchDepth = 0,
            context = window.opener;

        while (!!context && searchDepth < searchDepthMax)
        {
            if (typeof context.console !== 'undefined') return context.console;

            context = context.opener;
            searchDepth++;
        }

        return null;
    },
    log: function(message){
        var _console = this.getConsole();
        if (!!_console) _console.log(message);
    }
Max Venediktov
  • 262
  • 2
  • 8
-2

After having oh so many problems with this thing (it's hard to debug the error since if you open the developer console the error no longer happens!) I decided to make an overkill code to never have to bother with this ever again:

if (typeof window.console === "undefined")
    window.console = {};

if (typeof window.console.debug === "undefined")
    window.console.debug= function() {};

if (typeof window.console.log === "undefined")
    window.console.log= function() {};

if (typeof window.console.error === "undefined")
    window.console.error= function() {alert("error");};

if (typeof window.console.time === "undefined")
    window.console.time= function() {};

if (typeof window.console.trace === "undefined")
    window.console.trace= function() {};

if (typeof window.console.info === "undefined")
    window.console.info= function() {};

if (typeof window.console.timeEnd === "undefined")
    window.console.timeEnd= function() {};

if (typeof window.console.group === "undefined")
    window.console.group= function() {};

if (typeof window.console.groupEnd === "undefined")
    window.console.groupEnd= function() {};

if (typeof window.console.groupCollapsed === "undefined")
    window.console.groupCollapsed= function() {};

if (typeof window.console.dir === "undefined")
    window.console.dir= function() {};

if (typeof window.console.warn === "undefined")
    window.console.warn= function() {};

Personaly I only ever use console.log and console.error, but this code handles all the other functions as shown in the Mozzila Developer Network: https://developer.mozilla.org/en-US/docs/Web/API/console. Just put that code on the top of your page and you are done forever with this.

Hoffmann
  • 12,871
  • 13
  • 69
  • 87
-11

You can use console.log(...) directly in Firefox but not in IEs. In IEs you have to use window.console.

  • 11
    console.log and window.console.log refer to the same function in any browser which is even remotely conformant with ECMAscript. It is good practice to use the latter to avoid a local variable accidentally shadowing the global console object, but that has absolutely nothing to do with the choice of browser. console.log works fine in IE8, and AFAIK there is no logging capability at all in IE6/7. – Tgr Oct 26 '10 at 16:13