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?
Stub of console in TypeScript:
Paste the following at the top of your JavaScript (before using the console):
The function closure wrapper is to scope the variables as to not define any variables. This guards against both undefined
console
and undefinedconsole.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.
Another alternative is the
typeof
operator:Yet another alternative is to use a logging library, such as my own log4javascript.
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?
For a more robust solution, use this piece of code (taken from twitter's source code):
You can use the below to give an extra degree of insurance that you've got all bases covered. Using
typeof
first will avoid anyundefined
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 choselogMsg
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.