In which circumstances is window.console.log
defined in Internet Explorer 9?
Even when window.console.log
is defined, window.console.
How about...
console = { log : function(text) { alert(text); } }
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.
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:
function log()
{
"use strict";
if (typeof(console) !== "undefined" && console.log !== undefined)
{
try
{
console.log.apply(console, arguments);
}
catch (e)
{
var log = Function.prototype.bind.call(console.log, console);
log.apply(console, arguments);
}
}
}
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).
// 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;
}
}
}());
Reference:
https://github.com/h5bp/html5-boilerplate/blob/v5.0.0/dist/js/plugins.js
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
if (window.console)
console.log(msg)
this throws an exception in IE9 and will not work correctly. Do not do this
if (console)
console.log(msg)
A simple solution to this console.log problem is to define the following at the beginning of your JS code:
if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };
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.