Whats the best approach for preventing errors when console.log calls have been left in JavaScript and it is executed on Browsers without a console or with console deactivated. Is there a way it can be automatically overridden to become a javascript alert for example?
+2
A:
if(!window.console) console = {log: function(s) {alert(s);}};
You can of course add more of the functions that console normally has.
sje397
2010-07-16 15:03:19
A more complete version is [here](http://stackoverflow.com/questions/3265684/using-console-log-with-firebug-ok-locally-not-when-published-to-my-live-site/3265752#3265752)
sje397
2010-07-16 15:11:02
Note that the expression `if(!console)` will produce a `ReferenceError` if the `console` identifier hasn't been declared. That's why using the `typeof` operator, or checking `if (!window.console)` is recommended.
CMS
2010-07-16 15:12:27
@CMS - fixed, ta
sje397
2010-07-16 15:15:49
There's no need for parentheses around the `console`: `typeof` is an operator, not a function.
Tim Down
2010-07-16 15:11:58
@snaken - True, you'd have to add the check to each, not as simple as @sje397's solution.
Andy Robinson
2010-07-16 15:12:21
+3
A:
You have to check if the console
identifier is available, you can do it either by using the typeof
operator, or by checking window.console
, because if you access directly an identifier and it's not defined, you will get a ReferenceError.
For example:
if (typeof console == "undefined") {
window.console = {
log: function () {
// do nothing
}
};
console.warn = console.debug = console.log;
}
CMS
2010-07-16 15:08:46