【问题标题】:What happened to console.log in IE8?IE8 中的 console.log 发生了什么?
【发布时间】:2010-10-15 23:18:08
【问题描述】:

根据this post,它处于测试阶段,但尚未发布?

【问题讨论】:

  • console.log is 在 IE8 中,但在打开 DevTools 之前不会创建 console 对象。因此,调用console.log 可能会导致错误,例如,如果它发生在您有机会打开开发工具之前的页面加载中。 winning answer here 对此进行了更详细的解释。

标签: javascript logging internet-explorer-8 console


【解决方案1】:

console.log 仅在您打开开发工具后可用(F12 切换它的打开和关闭)。 有趣的是,在你打开它之后,你可以关闭它,然后仍然通过 console.log 调用发布到它,当你重新打开它时会看到这些。 我认为这是某种错误,可能会被修复,但我们会看到。

我可能会使用这样的东西:

function trace(s) {
  if ('console' in self && 'log' in console) console.log(s)
  // the line below you might want to comment out, so it dies silent
  // but nice for seeing when the console is available or not.
  else alert(s)
}

甚至更简单:

function trace(s) {
  try { console.log(s) } catch (e) { alert(s) }
}

【讨论】:

  • 无论哪种方式,您都不应该盲目调用 console.log,因为 $other-browsers 可能没有它,因此会因 JavaScript 错误而死。 +1
  • 你可能想在发布之前关闭跟踪;)
  • 在没有打开开发工具的情况下不记录是有道理的,但是如果这里真正令人困惑的决定是让它抛出异常而不是静默失败。
  • 我想指出像这样包装console.log 的一个缺点……您将看不到日志的来源。我发现这有时非常有用,此外,让每个控制台行都源自代码中完全相同的位置看起来是错误的。
  • alert 是邪恶的。使用警报时,某些代码的行为会有所不同,因为文档失去焦点,从而使错误更难诊断或在以前没有的地方创建错误。此外,如果您不小心在生产代码中留下了console.log,它是良性的(假设它没有爆炸)——只需默默地登录到控制台。如果您不小心在生产代码中留下了alert,那么用户体验就会被破坏。
【解决方案2】:

对于后备来说更好的是:

var alertFallback = true; if (typeof console === "undefined" || typeof console.log === "undefined") { console = {}; if (alertFallback) { console.log = function(msg) { alert(msg); }; } else { console.log = function() {}; } }

【讨论】:

  • 这太不切实际了——你怎么可能调试一个网站,每次调用console.log()都会引发警报。如果您的代码中有 10 次以上的 log() 调用怎么办。如果 msg 是一个对象怎么办? Walter's answer 作为起点更有意义。
  • @Precastic:人们将停止使用浏览器:P
  • 请参阅 my comment 幸运先生的回答。
  • 一个不显眼(虽然不完美)的备用备用方案是设置 document.title。至少它不会通过模式警报锁定浏览器。
【解决方案3】:

这是我对各种答案的看法。我想实际查看记录的消息,即使在它们被触发时我没有打开 IE 控制台,所以我将它们推送到我创建的 console.messages 数组中。我还添加了一个函数console.dump(),方便查看整个日志。 console.clear() 将清空消息队列。

此解决方案还“处理”其他控制台方法(我相信它们都源自Firebug Console API

最后,这个解决方案是IIFE的形式,所以它不会污染全局范围。回退函数参数在代码底部定义。

我只是将它放在我的主 JS 文件中,该文件包含在每个页面上,然后忘记它。

(function (fallback) {    

    fallback = fallback || function () { };

    // function to trap most of the console functions from the FireBug Console API. 
    var trap = function () {
        // create an Array from the arguments Object           
        var args = Array.prototype.slice.call(arguments);
        // console.raw captures the raw args, without converting toString
        console.raw.push(args);
        var message = args.join(' ');
        console.messages.push(message);
        fallback(message);
    };

    // redefine console
    if (typeof console === 'undefined') {
        console = {
            messages: [],
            raw: [],
            dump: function() { return console.messages.join('\n'); },
            log: trap,
            debug: trap,
            info: trap,
            warn: trap,
            error: trap,
            assert: trap,
            clear: function() { 
                  console.messages.length = 0; 
                  console.raw.length = 0 ;
            },
            dir: trap,
            dirxml: trap,
            trace: trap,
            group: trap,
            groupCollapsed: trap,
            groupEnd: trap,
            time: trap,
            timeEnd: trap,
            timeStamp: trap,
            profile: trap,
            profileEnd: trap,
            count: trap,
            exception: trap,
            table: trap
        };
    }

})(null); // to define a fallback function, replace null with the name of the function (ex: alert)

一些额外的信息

var args = Array.prototype.slice.call(arguments); 行从arguments 对象创建一个数组。这是必需的,因为arguments is not really an Array

trap() 是任何 API 函数的默认处理程序。我将参数传递给message,以便您获得传递给任何API 调用(不仅仅是console.log)的参数的日志。

编辑

我添加了一个额外的数组console.raw,它完全按照传递给trap() 的方式捕获参数。我意识到args.join(' ') 正在将对象转换为字符串"[object Object]",这有时可能是不可取的。感谢bfontaine 提供suggestion

【讨论】:

  • +1 这是唯一开始有意义的解决方案。在什么情况下您希望看到您明确发送到控制台的消息!
  • 很好的答案。真的很喜欢你提到的 IIFE 文章,可能是我迄今为止读过的最好的文章之一。您能否详细说明trap 函数中这两行的目的是什么:var args = Array.prototype.slice.call(arguments); var message = args.join(' ');?为什么要通过 this 将参数传递给消息?
  • @user1555863 我已经更新了我的答案来回答您的问题,请参阅代码下方的部分。
  • 我认为你的“console.clear()”函数的第二行应该是“console.raw.length = 0”,而不是“console.row.length = 0”。
【解决方案4】:

值得注意的是,IE8 中的console.log 并不是真正的Javascript 函数。它不支持applycall 方法。

【讨论】:

  • +1 这是我今天早上的准确错误。我正在尝试对 console.log 应用参数,而 IE8 讨厌我。
  • [笑话] 微软说“让我们的人覆盖控制台对象对我们来说是不安全的”:/
  • 我一直在使用:console.log=Function.prototype.bind.call(console.log,console); 来解决这个问题。
【解决方案5】:

假设您不关心警报的后备,这里有一个更简洁的方法来解决 Internet Explorer 的缺点:

var console=console||{"log":function(){}};

【讨论】:

  • +1 因为我在匿名函数中限定了我的代码范围,所以将控制台放入这样的变量中对我来说是最好的解决方案。帮助我不干扰其他库中正在进行的任何其他控制台挂钩。
  • 您希望在开发人员工具打开后立即开始记录。如果您将此解决方案放在长期存在的范围内(例如,将内部函数注册为回调),它将继续使用静默后备。
  • +1/-1 = 0: +1 因为该解决方案应该更多地基于防止 console.logs 破坏 IE 中的站点 - 不用于调试......如果你想调试,只需按 f12 并打开控制台 :) -1 因为您应该在覆盖之前检查控制台是否存在。
  • 一些IE插件定义了console和console.log,但都是空对象,不是函数。
【解决方案6】:

我真的很喜欢“orange80”发布的方法。它很优雅,因为您可以设置一次就忘记它。

其他方法要求你做一些不同的事情(每次都打电话给console.log()以外的其他东西),这只是自找麻烦……我知道我最终会忘记。

我更进一步,将代码包装在一个实用函数中,您可以在 javascript 的开头调用一次,只要它在任何日志记录之前即可。 (我正在将它安装在我公司的事件数据路由器产品中。它将有助于简化其新管理界面的跨浏览器设计。)

/**
 * Call once at beginning to ensure your app can safely call console.log() and
 * console.dir(), even on browsers that don't support it.  You may not get useful
 * logging on those browers, but at least you won't generate errors.
 * 
 * @param  alertFallback - if 'true', all logs become alerts, if necessary. 
 *   (not usually suitable for production)
 */
function fixConsole(alertFallback)
{    
    if (typeof console === "undefined")
    {
        console = {}; // define it if it doesn't exist already
    }
    if (typeof console.log === "undefined") 
    {
        if (alertFallback) { console.log = function(msg) { alert(msg); }; } 
        else { console.log = function() {}; }
    }
    if (typeof console.dir === "undefined") 
    {
        if (alertFallback) 
        { 
            // THIS COULD BE IMPROVED… maybe list all the object properties?
            console.dir = function(obj) { alert("DIR: "+obj); }; 
        }
        else { console.dir = function() {}; }
    }
}

【讨论】:

  • 很高兴你喜欢它 :-) 我使用它是因为你提到的确切原因——b/c 这是一个很好的安全性。将一些“console.log”语句放在您的代码中进行开发而忘记删除它们太容易了。至少如果你这样做,并将它放在你使用 console.log 的每个文件的顶部,你将永远不会让网站在客户的浏览器中中断,因为他们在 console.log 上失败了。以前救过我!不错的改进,顺便说一句:-)
  • “这太容易了……忘记删除它们”。我经常对临时调试日志做的一件有用的事情是在代码前面加上一个空注释 /**/console.log("...");,这样可以很容易地搜索和定位临时代码。
【解决方案7】:

如果您的所有 console.log 调用都“未定义”,这可能意味着您仍然加载了旧的 firebuglite (firebug.js)。它将覆盖 IE8 的 console.log 的所有有效功能,即使它们确实存在。无论如何,这就是发生在我身上的事情。

检查覆盖控制台对象的其他代码。

【讨论】:

    【解决方案8】:

    任何缺少控制台的浏览器的最佳解决方案是:

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

    【讨论】:

    • 这有一个明显的问题,即使用 console.group 或 console.GroupCollapsed 记录的对象或字符串将完全消失。这是不必要的,如果可用,它们应该映射到 console.log。
    【解决方案9】:

    答案太多了。我的解决方案是:

    globalNamespace.globalArray = new Array();
    if (typeof console === "undefined" || typeof console.log === "undefined") {
        console = {};
        console.log = function(message) {globalNamespace.globalArray.push(message)};   
    }
    

    简而言之,如果 console.log 不存在(或者在这种情况下,未打开),则将日志存储在全局命名空间数组中。这样一来,您就不会受到数百万条警报的困扰,并且您仍然可以在开发者控制台打开或关闭的情况下查看您的日志。

    【讨论】:

      【解决方案10】:

      这是我的“IE请不要崩溃”

      typeof console=="undefined"&&(console={});typeof console.log=="undefined"&&(console.log=function(){});
      

      【讨论】:

        【解决方案11】:
        if (window.console && 'function' === typeof window.console.log) { window.console.log(o); }

        【讨论】:

        • 你是说window.console.log() 可能在 IE8 中可用,即使 console.log() 不可用?
        • 这里的问题是typeof window.console.log === "object",而不是"function"
        【解决方案12】:

        我在github 上找到了这个:

        // usage: log('inside coolFunc', this, arguments);
        // paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
        window.log = function f() {
            log.history = log.history || [];
            log.history.push(arguments);
            if (this.console) {
                var args = arguments,
                    newarr;
                args.callee = args.callee.caller;
                newarr = [].slice.call(args);
                if (typeof console.log === 'object') log.apply.call(console.log, console, newarr);
                else console.log.apply(console, newarr);
            }
        };
        
        // make it safe to use console.log always
        (function(a) {
            function b() {}
            for (var c = "assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","), d; !! (d = c.pop());) {
                a[d] = a[d] || b;
            }
        })(function() {
            try {
                console.log();
                return window.console;
            } catch(a) {
                return (window.console = {});
            }
        } ());
        

        【讨论】:

          【解决方案13】:

          我在上面使用 Walter 的方法(请参阅:https://stackoverflow.com/a/14246240/3076102

          我混合了我在这里找到的解决方案https://stackoverflow.com/a/7967670 以正确显示对象。

          这意味着陷阱函数变为:

          function trap(){
              if(debugging){
                  // create an Array from the arguments Object           
                  var args = Array.prototype.slice.call(arguments);
                  // console.raw captures the raw args, without converting toString
                  console.raw.push(args);
                  var index;
                  for (index = 0; index < args.length; ++index) {
                      //fix for objects
                      if(typeof args[index] === 'object'){ 
                          args[index] = JSON.stringify(args[index],null,'\t').replace(/\n/g,'<br>').replace(/\t/g,'&nbsp;&nbsp;&nbsp;');
                      }
                  }
                  var message = args.join(' ');
                  console.messages.push(message);
                  // instead of a fallback function we use the next few lines to output logs
                  // at the bottom of the page with jQuery
                  if($){
                      if($('#_console_log').length == 0) $('body').append($('<div />').attr('id', '_console_log'));
                      $('#_console_log').append(message).append($('<br />'));
                  }
              }
          } 
          

          我希望这会有所帮助:-)

          【讨论】:

            【解决方案14】:

            我喜欢这种方法(使用 jquery 准备好的文档)...它甚至可以让您在 ie 中使用控制台...唯一需要注意的是,如果您在页面加载后打开 ie 的开发工具,则需要重新加载页面...

            考虑所有功能可能会更流畅,但我只使用日志,所以这就是我所做的。

            //one last double check against stray console.logs
            $(document).ready(function (){
                try {
                    console.log('testing for console in itcutils');
                } catch (e) {
                    window.console = new (function (){ this.log = function (val) {
                        //do nothing
                    }})();
                }
            });
            

            【讨论】:

              【解决方案15】:

              这是一个在开发者工具打开而不是在它们关闭时将登录到控制台的版本。

              (function(window) {
              
                 var console = {};
                 console.log = function() {
                    if (window.console && (typeof window.console.log === 'function' || typeof window.console.log === 'object')) {
                       window.console.log.apply(window, arguments);
                    }
                 }
              
                 // Rest of your application here
              
              })(window)
              

              【讨论】:

              • 不错,范围有限,可以支持IE8 DevTools在代码执行过程中打开的情况,但是在IE8中不起作用,console.log是一个对象,所以没有apply 方法。
              【解决方案16】:

              用 html 制作自己的控制台 .... ;-) 这可以改进,但您可以从以下开始:

              if (typeof console == "undefined" || typeof console.log === "undefined") {
                  var oDiv=document.createElement("div");
                  var attr = document.createAttribute('id'); attr.value = 'html-console';
                  oDiv.setAttributeNode(attr);
              
              
                  var style= document.createAttribute('style');
                  style.value = "overflow: auto; color: red; position: fixed; bottom:0; background-color: black; height: 200px; width: 100%; filter: alpha(opacity=80);";
                  oDiv.setAttributeNode(style);
              
                  var t = document.createElement("h3");
                  var tcontent = document.createTextNode('console');
                  t.appendChild(tcontent);
                  oDiv.appendChild(t);
              
                  document.body.appendChild(oDiv);
                  var htmlConsole = document.getElementById('html-console');
                  window.console = {
                      log: function(message) {
                          var p = document.createElement("p");
                          var content = document.createTextNode(message.toString());
                          p.appendChild(content);
                          htmlConsole.appendChild(p);
                      }
                  };
              }
              

              【讨论】:

                【解决方案17】:

                它适用于 IE8。按 F12 打开 IE8 的开发者工具。

                >>console.log('test')
                LOG: test
                

                【讨论】:

                • 在我的情况下这个问题“未定义”。
                • 正如 Lucky 先生指出的那样:“console.log 仅在您打开开发者工具后可用(F12 切换它的打开和关闭)。”
                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2016-02-28
                • 2014-02-28
                • 2010-10-02
                • 2020-03-14
                • 2011-04-09
                相关资源
                最近更新 更多