In which circumstances is window.console.log
defined in Internet Explorer 9?
Even when window.console.log
is defined, window.console.log.apply
and window.console.log.call
are undefined. Why is this?
[Related question for IE8: What happened to console.log in IE8?.]
console.log is only defined when the console is open. If you want to check for it in your code make sure you check for for it within the window property
this throws an exception in IE9 and will not work correctly. Do not do this
After reading the article from Marc Cliament's comment above, I've now changed my all-purpose cross-browser console.log function to look like this:
In Internet Explorer 9 (and 8), the
console
object is only exposed when the developer tools are opened for a particular tab. If you hide the developer tools window for that tab, theconsole
object remains exposed for each page you navigate to. If you open a new tab, you must also open the developer tools for that tab in order for theconsole
object to be exposed.The
console
object is not part of any standard and is an extension to the Document Object Model. Like other DOM objects, it is considered a host object and is not required to inherit fromObject
, nor its methods fromFunction
, like native ECMAScript functions and objects do. This is the reasonapply
andcall
are undefined on those methods. In IE 9, most DOM objects were improved to inherit from native ECMAScript types. As the developer tools are considered an extension to IE (albeit, a built-in extension), they clearly didn't receive the same improvements as the rest of the DOM.For what it's worth, you can still use some
Function.prototype
methods onconsole
methods with a littlebind()
magic:I would like to mention that IE9 does not raise the error if you use console.log with developer tools closed on all versions of Windows. On XP it does, but on Windows 7 it doesn't. So if you dropped support for WinXP in general, you're fine using console.log directly.
A simple solution to this console.log problem is to define the following at the beginning of your JS code:
This works for me in all browsers. This creates a dummy function for console.log when the debugger is not active. When the debugger is active, the method console.log is defined and executes normally.
I know this is a very old question but feel this adds a valuable alternative of how to deal with the console issue. Place the following code before any call to console.* (so your very first script).
Reference:
https://github.com/h5bp/html5-boilerplate/blob/v5.0.0/dist/js/plugins.js