Apr
24
Logging Objects to the Console in Internet Explorer
Warning: Please consider that this post is over 8 years old and the content may no longer be relevant.
Compared to other browsers, IE’s JavaScript console is pretty lacking in it’s ability to log objects, they just appear as [Object object]. As a work around for this below is a shim that will JSON.stringify any objects that are passed as parameters to console.log (or it’s sister functions like error, warn…).
// Because IE11 doesn't support logging objects, this script stringifies objects passed to the console for IE.
(function (console) {
var fns = ['trace', 'debug', 'info', 'warn', 'error', 'log'];
var orig = {};
function isIE() {
return (navigator.appName == 'Microsoft Internet Explorer' ||
(navigator.appName == 'Netscape' &&
new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})").exec(navigator.userAgent) !== null));
}
function fixObjectLogging(fn) {
orig[fn] = console[fn];
console[fn] = function () {
var args = Array.prototype.slice.call(arguments);
for (var i = 0; i < args.length; i++) {
if (typeof(args[i]) === "object")
args[i] = JSON.stringify(args[i]);
}
Function.prototype.apply.apply(orig[fn], [console, args]);
};
}
function init() {
if (!isIE()) return;
for (var i = 0; i < fns.length; i++) {
var fn = fns[i];
if (console[fn]) {
fixObjectLogging(fn);
}
}
}
init();
}(window.console));
You’ll also find that IE doesn’t record console output while the developer tools are open, to enable this in IE11 go to Settings (The Gear) > Internet options > Advanced > Check ‘Always record developer console messages’.