代码之家  ›  专栏  ›  技术社区  ›  leeand00

IE8中的console.log发生了什么?

  •  250
  • leeand00  · 技术社区  · 16 年前

    根据 this post

    17 回复  |  直到 13 年前
        1
  •  258
  •   Mister Lucky    13 年前

    我认为这是一种缺陷,可能会被修复,但我们将拭目以待。

    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) }
    }
    
        2
  •  230
  •   jpswain    14 年前

    更好的回退方法是:

    
       var alertFallback = true;
       if (typeof console === "undefined" || typeof console.log === "undefined") {
         console = {};
         if (alertFallback) {
             console.log = function(msg) {
                  alert(msg);
             };
         } else {
             console.log = function() {};
         }
       }
    
    
        3
  •  57
  •   Community CDub    8 年前

    这是我对各种答案的看法。我想实际查看记录的消息,即使在它们被触发时我没有打开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 陷阱() . 我意识到 args.join(' ') "[object Object]" 这有时可能是不可取的。谢谢 bfontaine 对于 suggestion .

        4
  •  52
  •   James Wheare    15 年前

    值得注意的是 console.log apply call 方法。

        5
  •  44
  •   Leif Wickland    13 年前

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

    var console=console||{"log":function(){}};
    
        6
  •  24
  •   Benoit Garret    13 年前

    我真的很喜欢“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() {}; }
        }
    }
    
        7
  •  8
  •   user168290    15 年前

    检查覆盖console对象的其他代码。

        8
  •  6
  •   GitaarLAB    10 年前

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

    // 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;
            }
        }
    }());
    
        9
  •  4
  •   Nishi    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
  •  3
  •   BrunoLM    11 年前

    typeof console=="undefined"&&(console={});typeof console.log=="undefined"&&(console.log=function(){});
    
        11
  •  2
  •   Balázs Németh    14 年前
    window.console.log(o);
    }
    
        12
  •  2
  •   Sam Jones    11 年前

    我发现这个 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
  •  2
  •   Community CDub    8 年前

    我从上面使用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
  •  1
  •   user3560902    11 年前

    我喜欢这种方法(使用jquery的docready)。。。它可以让你使用控制台,甚至在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
  •  1
  •   George Reith    10 年前

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

    (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)
    
        16
  •  1
  •   Alexandre Assouad    10 年前

    用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
  •  0
  •   Konstantin Tarkus    16 年前

    它在IE8中工作。点击F12打开IE8的开发者工具。

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