'console'是Internet Explorer的未定义错误

use*_*114 374 javascript internet-explorer internet-explorer-8 ie-developer-tools

我正在使用Firebug,并且有一些声明:

console.log("...");
Run Code Online (Sandbox Code Playgroud)

在我的页面中.在IE8(也可能是早期版本)中,我收到脚本错误,说"控制台"未定义.我试着把它放在我的页面顶部:

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

我仍然得到错误.有什么办法摆脱错误?

ken*_*ytm 377

尝试

if (!window.console) console = ...
Run Code Online (Sandbox Code Playgroud)

未定义的变量不能直接引用.但是,所有全局变量都是全局上下文的同名属性(window在浏览器的情况下),并且访问未定义的属性很好.

或者if (typeof console === 'undefined') console = ...如果你想避免使用魔法变量window,请参阅@Tim Down的答案.

  • 为了清楚使用它的其他人,请放置`<script type ="text/javascript"> if(!window.console)console = {log:function(){}}; </ script>`位于页面顶部!谢谢肯尼. (159认同)
  • 该死的...你建立了一个不错的网站,为你喜欢的浏览器开发它.最后你花了4-5个小时使其与所有其他的现代浏览器兼容,然后你花费4-5天让它与IE兼容. (64认同)
  • 怎么样`var console = console || {log:function(){}};` (11认同)
  • @lorddev要使用该简写,您需要包含`window`:`var console = window.console || {log:function(){}};` (9认同)
  • 这个答案的问题是,如果你使用另一个名称,如debug,warn,count with browser缺少控制台将抛出异常,请参阅更好的方法来做到这一点http://stackoverflow.com/a/16916941/2274855 (6认同)
  • 仅供参考,killianmcc发布的上述代码只是防止了错误,但实际的`console.log()`函数绝对没有任何作用. (4认同)

Pet*_*eng 317

将以下内容粘贴到JavaScript的顶部(在使用控制台之前):

/**
 * Protect window.console method calls, e.g. console is not defined on IE
 * unless dev tools are open, and IE doesn't define console.debug
 * 
 * Chrome 41.0.2272.118: debug,error,info,log,warn,dir,dirxml,table,trace,assert,count,markTimeline,profile,profileEnd,time,timeEnd,timeStamp,timeline,timelineEnd,group,groupCollapsed,groupEnd,clear
 * Firefox 37.0.1: log,info,warn,error,exception,debug,table,trace,dir,group,groupCollapsed,groupEnd,time,timeEnd,profile,profileEnd,assert,count
 * Internet Explorer 11: select,log,info,warn,error,debug,assert,time,timeEnd,timeStamp,group,groupCollapsed,groupEnd,trace,clear,dir,dirxml,count,countReset,cd
 * Safari 6.2.4: debug,error,log,info,warn,clear,dir,dirxml,table,trace,assert,count,profile,profileEnd,time,timeEnd,timeStamp,group,groupCollapsed,groupEnd
 * Opera 28.0.1750.48: debug,error,info,log,warn,dir,dirxml,table,trace,assert,count,markTimeline,profile,profileEnd,time,timeEnd,timeStamp,timeline,timelineEnd,group,groupCollapsed,groupEnd,clear
 */
(function() {
  // Union of Chrome, Firefox, IE, Opera, and Safari console methods
  var methods = ["assert", "cd", "clear", "count", "countReset",
    "debug", "dir", "dirxml", "error", "exception", "group", "groupCollapsed",
    "groupEnd", "info", "log", "markTimeline", "profile", "profileEnd",
    "select", "table", "time", "timeEnd", "timeStamp", "timeline",
    "timelineEnd", "trace", "warn"];
  var length = methods.length;
  var console = (window.console = window.console || {});
  var method;
  var noop = function() {};
  while (length--) {
    method = methods[length];
    // define undefined methods as noops to prevent errors
    if (!console[method])
      console[method] = noop;
  }
})();
Run Code Online (Sandbox Code Playgroud)

函数闭包装置将变量的范围限定为不定义任何变量.这可以防止未定义console和未定义console.debug(以及其他缺少的方法).

编辑:我注意到HTML5 Boilerplate在其js/plugins.js文件中使用类似的代码,如果你正在寻找一个(可能)保持最新的解决方案.

  • 为什么这个答案很少支持?这是发布在这里的最完整的一个. (14认同)
  • 什么时候会发生这种情况?此代码应仅定义尚未定义的元素. (5认同)
  • 我认为无论哪种方式 - (function(){...}())或(function(){...})() - 实际上都有效 (4认同)

Tim*_*own 73

另一个选择是typeof运营商:

if (typeof console == "undefined") {
    this.console = {log: function() {}};
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用日志库,例如我自己的log4javascript.

  • @yckart:不.`typeof`保证返回一个字符串,`"undefined"`是一个字符串.当两个操作数具有相同的类型时,指定`==`和`===`来执行完全相同的步骤.使用`typeof x =="undefined"`是一种坚如磐石的方法来测试在任何范围和任何ECMAScript 3兼容环境中是否未定义`x`. (8认同)
  • 多么令人困惑的讨论.+1到原始答案.如果我能给+2我会提供一个链接到你自己的log4javascript.谢谢OP! (2认同)

Vin*_*aes 47

要获得更强大的解决方案,请使用这段代码(取自twitter的源代码):

// 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;
        }
    }
}());
Run Code Online (Sandbox Code Playgroud)


ibl*_*ish 13

在我的脚本中,我要么使用速记:

window.console && console.log(...) // only log if the function exists
Run Code Online (Sandbox Code Playgroud)

或者,如果编辑每个console.log行是不可能或不可行的,我会创建一个虚假的控制台:

// check to see if console exists. If not, create an empty object for it,
// then create and empty logging function which does nothing. 
//
// REMEMBER: put this before any other console.log calls
!window.console && (window.console = {} && window.console.log = function () {});
Run Code Online (Sandbox Code Playgroud)

  • 语法错误.为什么不只是`if(!console){console = {}; console.log = function(){};}` (2认同)

小智 10

您可以使用console.log(),如果你有Developer Tools在IE8打开,也可以使用Console脚本选项卡上的文本框中.

  • 如果你忘记扫除控制台的代码,那就不好了.IE8中的错误将阻止您的JS代码工作 (7认同)

ins*_*ign 7

if (typeof console == "undefined") {
  this.console = {
    log: function() {},
    info: function() {},
    error: function() {},
    warn: function() {}
  };
}
Run Code Online (Sandbox Code Playgroud)


TWi*_*Rob 7

基于之前的两个答案

以及.的文件

这是该问题的尽力实现,这意味着如果存在实际存在的console.log,它将通过console.log填补不存在的方法的空白.

例如,对于IE6/7,您可以使用alert替换日志记录(愚蠢但有效)然后包含下面的怪物(我称之为console.js):[随意删除您认为合适的评论,我将它们留作参考,最小化器可以解决它们]:

<!--[if lte IE 7]>
<SCRIPT LANGUAGE="javascript">
    (window.console = window.console || {}).log = function() { return window.alert.apply(window, arguments); };
</SCRIPT>
<![endif]-->
<script type="text/javascript" src="console.js"></script>
Run Code Online (Sandbox Code Playgroud)

和console.js:

    /**
     * Protect window.console method calls, e.g. console is not defined on IE
     * unless dev tools are open, and IE doesn't define console.debug
     */
    (function() {
        var console = (window.console = window.console || {});
        var noop = function () {};
        var log = console.log || noop;
        var start = function(name) { return function(param) { log("Start " + name + ": " + param); } };
        var end = function(name) { return function(param) { log("End " + name + ": " + param); } };

        var methods = {
            // Internet Explorer (IE 10): http://msdn.microsoft.com/en-us/library/ie/hh772169(v=vs.85).aspx#methods
            // assert(test, message, optionalParams), clear(), count(countTitle), debug(message, optionalParams), dir(value, optionalParams), dirxml(value), error(message, optionalParams), group(groupTitle), groupCollapsed(groupTitle), groupEnd([groupTitle]), info(message, optionalParams), log(message, optionalParams), msIsIndependentlyComposed(oElementNode), profile(reportName), profileEnd(), time(timerName), timeEnd(timerName), trace(), warn(message, optionalParams)
            // "assert", "clear", "count", "debug", "dir", "dirxml", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "msIsIndependentlyComposed", "profile", "profileEnd", "time", "timeEnd", "trace", "warn"

            // Safari (2012. 07. 23.): https://developer.apple.com/library/safari/#documentation/AppleApplications/Conceptual/Safari_Developer_Guide/DebuggingYourWebsite/DebuggingYourWebsite.html#//apple_ref/doc/uid/TP40007874-CH8-SW20
            // assert(expression, message-object), count([title]), debug([message-object]), dir(object), dirxml(node), error(message-object), group(message-object), groupEnd(), info(message-object), log(message-object), profile([title]), profileEnd([title]), time(name), markTimeline("string"), trace(), warn(message-object)
            // "assert", "count", "debug", "dir", "dirxml", "error", "group", "groupEnd", "info", "log", "profile", "profileEnd", "time", "markTimeline", "trace", "warn"

            // Firefox (2013. 05. 20.): https://developer.mozilla.org/en-US/docs/Web/API/console
            // debug(obj1 [, obj2, ..., objN]), debug(msg [, subst1, ..., substN]), dir(object), error(obj1 [, obj2, ..., objN]), error(msg [, subst1, ..., substN]), group(), groupCollapsed(), groupEnd(), info(obj1 [, obj2, ..., objN]), info(msg [, subst1, ..., substN]), log(obj1 [, obj2, ..., objN]), log(msg [, subst1, ..., substN]), time(timerName), timeEnd(timerName), trace(), warn(obj1 [, obj2, ..., objN]), warn(msg [, subst1, ..., substN])
            // "debug", "dir", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "time", "timeEnd", "trace", "warn"

            // Chrome (2013. 01. 25.): https://developers.google.com/chrome-developer-tools/docs/console-api
            // assert(expression, object), clear(), count(label), debug(object [, object, ...]), dir(object), dirxml(object), error(object [, object, ...]), group(object[, object, ...]), groupCollapsed(object[, object, ...]), groupEnd(), info(object [, object, ...]), log(object [, object, ...]), profile([label]), profileEnd(), time(label), timeEnd(label), timeStamp([label]), trace(), warn(object [, object, ...])
            // "assert", "clear", "count", "debug", "dir", "dirxml", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "profile", "profileEnd", "time", "timeEnd", "timeStamp", "trace", "warn"
            // Chrome (2012. 10. 04.): https://developers.google.com/web-toolkit/speedtracer/logging-api
            // markTimeline(String)
            // "markTimeline"

            assert: noop, clear: noop, trace: noop, count: noop, timeStamp: noop, msIsIndependentlyComposed: noop,
            debug: log, info: log, log: log, warn: log, error: log,
            dir: log, dirxml: log, markTimeline: log,
            group: start('group'), groupCollapsed: start('groupCollapsed'), groupEnd: end('group'),
            profile: start('profile'), profileEnd: end('profile'),
            time: start('time'), timeEnd: end('time')
        };

        for (var method in methods) {
            if ( methods.hasOwnProperty(method) && !(method in console) ) { // define undefined methods as best-effort methods
                console[method] = methods[method];
            }
        }
    })();
Run Code Online (Sandbox Code Playgroud)

  • 是.`var x = {a:1,b:2}; Object.prototype.surprise ='我在你的objectz'; for(var f in x){console.log(f,x [f]);}`你永远不知道库对你正在使用的对象的继承链中的对象做了什么.因此,javascript代码质量工具(如jshint和jslint)的建议使用`hasOwnProperty`. (3认同)

bon*_*nez 6

在IE9中,如果未打开控制台,则此代码:

alert(typeof console);
Run Code Online (Sandbox Code Playgroud)

将显示"对象",但此代码

alert(typeof console.log);
Run Code Online (Sandbox Code Playgroud)

将抛出TypeError异常,但不返回undefined值;

因此,保证版本的代码看起来类似于:

try {
    if (window.console && window.console.log) {
        my_console_log = window.console.log;
    }
} catch (e) {
    my_console_log = function() {};
}
Run Code Online (Sandbox Code Playgroud)

  • 有见识的答案. (2认同)

Rub*_*rop 6

我只在我的代码中使用console.log.所以我包括一个非常短的2班轮

var console = console || {};
console.log = console.log || function(){};
Run Code Online (Sandbox Code Playgroud)