【问题标题】:'console' is undefined error for Internet Explorer“控制台”是 Internet Explorer 的未定义错误
【发布时间】:2011-03-20 14:12:03
【问题描述】:

我正在使用 Firebug,并且有一些类似的语句:

console.log("...");

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

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

我仍然得到错误。有什么办法可以消除错误?

【问题讨论】:

标签: javascript internet-explorer internet-explorer-8 ie-developer-tools


【解决方案1】:

试试

if (!window.console) console = ...

无法直接引用未定义的变量。但是,所有全局变量都是与全局上下文同名的属性(window 在浏览器的情况下),访问未定义的属性是可以的。

如果您想避免魔术变量window,请使用if (typeof console === 'undefined') console = ...,请参阅@Tim Down's answer

【讨论】:

  • 为了让其他使用它的人清楚,请将&lt;script type="text/javascript"&gt; if (!window.console) console = {log: function() {}}; &lt;/script&gt; 放在页面顶部!谢谢肯尼。
  • var console = console || { log: function() {} };怎么样
  • @lorddev 要使用该速记,您需要包含 window: var console = window.console || { log: function() {} };
  • 该死的......你建立了一个不错的网站,为你最喜欢的浏览器开发它。最后,您花费 4-5 小时使其与所有其他现代浏览器兼容,然后您花费 4-5 天使其与 IE 兼容。
  • 该答案的问题是,如果您使用其他名称,如调试、警告、计数,缺少控制台的浏览器将引发异常,请参阅更好的方法stackoverflow.com/a/16916941/2274855
【解决方案2】:

在您的 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;
  }
})();

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

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

【讨论】:

  • 为什么这个答案的点赞数这么少?这是这里发布的最完整的一个。
  • 因为日期。绝对同意正确的工作解决方案。我认为这个话题需要缓和。抱歉英语不好。
  • 相当完整,只是它不会尝试将日志记录重定向到日志函数(如果存在),因此所有日志都会丢失
  • 这到底什么时候会发生?这段代码应该只定义尚未定义的元素。
  • 我认为无论哪种方式 - (function(){...}()) 或 (function(){...})() - 都有效
【解决方案3】:

另一种选择是typeof 运算符:

if (typeof console == "undefined") {
    this.console = {log: function() {}};
}

另一种选择是使用日志库,例如我自己的log4javascript

【讨论】:

  • 不过,最好将未声明的赋值更改为正确的声明。
  • 您的意思是使用var?那只会混淆这里的事情。还是您的意思是分配给window.console 而不是console
  • 使用var。为什么会在这里混淆?
  • 多么令人困惑的讨论。 +1 原始答案。如果我能给 +2 我会为您提供一个链接到您自己的 log4javascript。谢谢奥普!
  • @yckart:不。typeof 保证返回一个字符串,"undefined" 是一个字符串。当两个操作数属于同一类型时,指定===== 执行完全相同的步骤。使用typeof x == "undefined" 是测试x 在任何范围和任何符合ECMAScript 3 的环境中是否未定义的可靠方法。
【解决方案4】:

要获得更强大的解决方案,请使用这段代码(取自 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;
        }
    }
}());

【讨论】:

    【解决方案5】:

    在我的脚本中,我要么使用简写:

    window.console && console.log(...) // only log if the function exists
    

    或者,如果无法编辑每个 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 () {});
    

    【讨论】:

    • 语法错误。为什么不只是if(!console) {console = {} ; console.log = function(){};}
    • 或者不仅仅是!window.console &amp;&amp; (window.console = { log: function () { } });
    【解决方案6】:

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

    【讨论】:

    • 如果忘记刷控制台代码就不好了。 IE8 中的错误会阻止你的 JS 代码工作
    【解决方案7】:
    if (typeof console == "undefined") {
      this.console = {
        log: function() {},
        info: function() {},
        error: function() {},
        warn: function() {}
      };
    }
    

    【讨论】:

    • 警告购买者:这应该在thiswindow的全局级别定义。
    【解决方案8】:

    根据之前的两个回答

    和文档

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

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

    <!--[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>
    

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

    【讨论】:

    • 我不确定在 for 循环中是否需要 methods.hasOwnProperty(method) &amp;&amp;
    • 我确定你确实需要它。
    • 在 Chrome 的控制台中做了一个快速测试:&gt; x = { a: 1, b: 2} --> Object {a: 1, b: 2}for(var f in x) {console.log(f + " " + x[f]);} 'end' --> a 1 b 2 "end"。所以创建的匿名对象没有任何附加属性,methods 只是在for 循环之前创建。是否有可能破解上述内容?
    • 是的。 var x = { a: 1, b: 2}; Object.prototype.surprise = 'I\'m in yer objectz'; for (var f in x) {console.log(f, x[f]);} 你永远不知道库对你正在使用的对象的继承链中的对象做了什么。因此jshint和jslint等javascript代码质量工具推荐使用hasOwnProperty
    【解决方案9】:

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

    【讨论】:

      【解决方案10】:

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

      var console = console || {};
      console.log = console.log || function(){};
      

      【讨论】:

      • 它是如何工作的......我没有看到任何 console.log 行打印到 IE 浏览器,我已经测试了 2 个不同的系统,其中 1 - console.log 正在工作,2 系统它的不是。我在两个系统中都尝试过,但在两个系统中都看不到任何日志。
      【解决方案11】:

      注意到 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)

      【讨论】:

        【解决方案12】:

        我正在使用fauxconsole;我对 css 进行了一些修改,使它看起来更好,但效果很好。

        【讨论】:

          【解决方案13】:

          要在 IE 中调试,请查看此log4javascript

          【讨论】:

          • 这很棒,尤其是我的 IE8 控制台没有输出任何东西。
          • @Firsh 感谢您的 cmets。
          • 我在这里寻找对另一个问题的评论,说“无耻的自我推销”,或者我不知道 - 类似 - 有人说他创造了这个 scipt,是你吗?我已经关闭了那个标签。无论如何,它是一个非常棒的工具,对我的项目非常有用。
          • @Firsh 我没有创建这个脚本,我是像你一样受益于工具的人。
          【解决方案14】:

          对于仅限于 console.log 的 IE8 或控制台支持(无调试、跟踪等),您可以执行以下操作:

          • 如果控制台或 console.log 未定义:为 控制台功能(跟踪、调试、日志等)

            window.console = { debug : function() {}, ...};

          • 如果定义了console.log(IE8)并且没有定义console.debug(任何其他):将所有日志记录功能重定向到console.log,这允许保留这些日志!

            window.console = { debug : window.console.log, ...};

          不确定各种 IE 版本中的断言支持,但欢迎提出任何建议。还在这里发布了这个答案:How can I use console logging in Internet Explorer?

          【讨论】:

            【解决方案15】:
            console = console || { 
                debug: function(){}, 
                log: function(){}
                ...
            }
            

            【讨论】:

              【解决方案16】:

              TypeScript 中的控制台存根:

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

              【讨论】:

                【解决方案17】:

                您可以使用以下内容为您已涵盖所有基础的额外保险提供一定程度的保障。首先使用typeof 将避免任何undefined 错误。使用=== 还将确保类型的名称实际上是字符串“未定义”。最后,您需要向函数签名添加一个参数(我随意选择了logMsg)以确保一致性,因为您确实将要打印到控制台的任何内容传递给日志函数。这也使您的智能感知准确,并避免您的 JS IDE 中的任何警告/错误。

                if(!window.console || typeof console === "undefined") {
                  var console = { log: function (logMsg) { } };
                }
                

                【讨论】:

                  【解决方案18】:

                  有时控制台可以在 IE8/9 中工作,但有时会失败。这种不稳定的行为取决于您是否打开了开发人员工具,并且在 stackoverflow 问题 Does IE9 support console.log, and is it a real function?

                  中进行了描述

                  【讨论】:

                    【解决方案19】:

                    在 IE9 的子窗口中运行 console.log 时遇到类似的问题,由 window.open 函数创建。

                    似乎在这种情况下,控制台仅在父窗口中定义,在子窗口中未定义,直到您刷新它们。同样适用于子窗口的子级。

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

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

                    【讨论】:

                      【解决方案20】:

                      在这个东西遇到了这么多问题之后(很难调试错误,因为如果你打开开发者控制台,错误就不会再发生了!)我决定编写一个矫枉过正的代码,再也不用为此烦恼了:

                      if (typeof window.console === "undefined")
                          window.console = {};
                      
                      if (typeof window.console.debug === "undefined")
                          window.console.debug= function() {};
                      
                      if (typeof window.console.log === "undefined")
                          window.console.log= function() {};
                      
                      if (typeof window.console.error === "undefined")
                          window.console.error= function() {alert("error");};
                      
                      if (typeof window.console.time === "undefined")
                          window.console.time= function() {};
                      
                      if (typeof window.console.trace === "undefined")
                          window.console.trace= function() {};
                      
                      if (typeof window.console.info === "undefined")
                          window.console.info= function() {};
                      
                      if (typeof window.console.timeEnd === "undefined")
                          window.console.timeEnd= function() {};
                      
                      if (typeof window.console.group === "undefined")
                          window.console.group= function() {};
                      
                      if (typeof window.console.groupEnd === "undefined")
                          window.console.groupEnd= function() {};
                      
                      if (typeof window.console.groupCollapsed === "undefined")
                          window.console.groupCollapsed= function() {};
                      
                      if (typeof window.console.dir === "undefined")
                          window.console.dir= function() {};
                      
                      if (typeof window.console.warn === "undefined")
                          window.console.warn= function() {};
                      

                      就我个人而言,我只使用过console.log 和console.error,但是这段代码处理了Mozzila 开发者网络中显示的所有其他功能:https://developer.mozilla.org/en-US/docs/Web/API/console。 只需将该代码放在页面顶部,就可以永远完成。

                      【讨论】:

                        【解决方案21】:

                        您可以在 Firefox 中直接使用 console.log(...),但不能在 IE 中使用。在 IE 中你必须使用 window.console。

                        【讨论】:

                        • console.log 和 window.console.log 指的是任何浏览器中的相同功能,甚至远程符合 ECMAscript。使用后者来避免局部变量意外遮蔽全局控制台对象是一种很好的做法,但这与浏览器的选择完全无关。 console.log 在 IE8 中运行良好,而 AFAIK 在 IE6/7 中根本没有日志记录功能。
                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2011-07-17
                        • 2019-01-01
                        • 1970-01-01
                        相关资源
                        最近更新 更多