Internet Explorer 9在哪些情况下定义window.console.log ?

即使定义了window.console.log, window.console.log.apply和window.console.log.call也是未定义的。为什么会这样?

[IE8的相关问题:在IE8中console.log发生了什么?]


在Internet Explorer 9(和8)中,只有当为特定选项卡打开开发人员工具时,控制台对象才会公开。如果隐藏该选项卡的开发人员工具窗口,则控制台对象将为您导航到的每个页面保持暴露。如果打开一个新选项卡,还必须打开该选项卡的开发人员工具,以便公开控制台对象。

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 from Object, nor its methods from Function, like native ECMAScript functions and objects do. This is the reason apply and call 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.

不管怎样,你仍然可以使用一些函数。带有bind()魔法的控制台方法的原型方法:

var log = Function.prototype.bind.call(console.log, console);
log.apply(console, ["this", "is", "a", "test"]);
//-> "thisisatest"

console.log问题的一个简单解决方案是在JS代码的开头定义以下内容:

if (!window.console) window.console = {};
if (!window.console.log) window.console.log = function () { };

这在所有浏览器中都适用。这将在调试器未激活时为console.log创建一个虚拟函数。当调试器处于活动状态时,将定义console.log方法并正常执行。


如何……

console = { log : function(text) { alert(text); } }

在阅读了Marc climate上面的评论后,我现在改变了我的多功能跨浏览器console.log函数,如下所示:

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);
        }
    }
}

console.log仅在控制台打开时定义。如果你想在你的代码中检查它,请确保在window属性中检查它

if (window.console)
    console.log(msg)

这会在IE9中抛出一个异常,并且不能正常工作。不要这样做

if (console) 
    console.log(msg)

我知道这是一个非常古老的问题,但我认为这为如何处理主机问题提供了一个有价值的选择。在任何对控制台的调用之前放置以下代码。*(你的第一个剧本)。

// 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;
        }
    }
}());

参考: https://github.com/h5bp/html5-boilerplate/blob/v5.0.0/dist/js/plugins.js


我想说的是,如果你在所有版本的Windows上关闭开发者工具使用console.log, IE9不会引发这个错误。XP系统有,但Windows 7系统没有。 所以如果你放弃了对WinXP的支持,你可以直接使用console.log。