我使用Firebug,并有一些语句像:

console.log("...");

在我的页面上。在IE8(可能是更早的版本),我得到脚本错误说“控制台”是未定义的。我试着把这个放在我页面的顶部:

<script type="text/javascript">
    if (!console) console = {log: function() {}};
</script>

我还是会得到错误。有办法消除错误吗?


当前回答

在TypeScript中控制台的存根:

if (!window.console) {
console = {
    assert: () => undefined,
    clear: () => undefined,
    count: () => undefined,
    debug: () => undefined,
    dir: () => undefined,
    dirxml: () => undefined,
    error: () => undefined,
    group: () => undefined,
    groupCollapsed: () => undefined,
    groupEnd: () => undefined,
    info: () => undefined,
    log: () => undefined,
    msIsIndependentlyComposed: (e: Element) => false,
    profile: () => undefined,
    profileEnd: () => undefined,
    select: () => undefined,
    time: () => undefined,
    timeEnd: () => undefined,
    trace: () => undefined,
    warn: () => undefined,
    }
};

其他回答

我使用的是fauxconsole;我修改了css一点,使它看起来更好,但工作得很好。

在IE9中,如果控制台未打开,以下代码:

alert(typeof console);

会显示“对象”,但这个代码

alert(typeof console.log);

将抛出TypeError异常,但不返回未定义的值;

因此,保证版本的代码将类似于:

try {
    if (window.console && window.console.log) {
        my_console_log = window.console.log;
    }
} catch (e) {
    my_console_log = function() {};
}
if (typeof console == "undefined") {
  this.console = {
    log: function() {},
    info: function() {},
    error: function() {},
    warn: function() {}
  };
}

注意到OP在IE中使用Firebug,所以假设它是Firebug Lite。当调试器窗口打开时,在IE中定义控制台,这是一种奇怪的情况,但是当Firebug已经在运行时会发生什么呢?不确定,但在这种情况下,"firebugx.js"方法可能是一个很好的测试方法:

来源:

https://code.google.com/p/fbug/source/browse/branches/firebug1.2/lite/firebugx.js?r=187

    if (!window.console || !console.firebug) {
        var names = [
            "log", "debug", "info", "warn", "error", "assert",
            "dir","dirxml","group","groupEnd","time","timeEnd",
            "count","trace","profile","profileEnd"
        ];
        window.console = {};
        for (var i = 0; i < names.length; ++i)
            window.console[names[i]] = function() {}
    }

(更新链接12/2014)

在IE9的子窗口中运行console.log时遇到类似问题,由window创建。打开功能。

在这种情况下,控制台似乎只在父窗口中定义,在刷新子窗口之前没有定义。同样适用于子窗口的子窗口。

我处理这个问题通过包装log在下一个函数(下面是模块的片段)

getConsole: function()
    {
        if (typeof console !== 'undefined') return console;

        var searchDepthMax = 5,
            searchDepth = 0,
            context = window.opener;

        while (!!context && searchDepth < searchDepthMax)
        {
            if (typeof context.console !== 'undefined') return context.console;

            context = context.opener;
            searchDepth++;
        }

        return null;
    },
    log: function(message){
        var _console = this.getConsole();
        if (!!_console) _console.log(message);
    }