Is there a way to log to console without breaking code under IE?

前端 未结 6 554
后悔当初
后悔当初 2021-02-05 18:50

I\'m trying to use console.log to put some logging into the javascript side of my program. I noticed, though, that unless the dev console is open in IE, JS basically stops worki

相关标签:
6条回答
  • 2021-02-05 19:29

    I use this snippet myself

    if (! ('console' in window) ) {
    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() {};
    }else {
    /*if it exists but doesn't contain all the same methods....silly ie*/
    var names = ['log', 'debug', 'info', 'warn', 'error', 'assert', 'dir', 'dirxml', 'group', 'groupEnd', 'time', 'timeEnd', 'count', 'trace', 'profile', 'profileEnd'];
    for (var i = 0; i < names.length; ++i) if(!window.console[names[i]])window.console[names[i]] = function() {};
    };
    
    0 讨论(0)
  • 2021-02-05 19:39

    I solved it by using the "fake console" described above, to prevent the script execution breaking. It is included only for InternetExplorer < 10. I include this in my html head:

    <!--[if lte IE 10]>
      <script> if (typeof console === "undefined") console = { log: function() { } }; </script>
    <![endif]-->
    
    0 讨论(0)
  • 2021-02-05 19:42

    IE has its own console, and you wont want to override console if you're using firebug lite. Just make sure that console exists when log gets called:

    if (window.console) console.log('foo bar baz', fizz, buzz);
    

    Better yet, use && to shortcut:

    window.console && console.log('foo bar baz', fizz, buzz);
    
    0 讨论(0)
  • 2021-02-05 19:50
    function log(log){
      try{
         console.log( log); 
      }catch(err){}
    }
    
    0 讨论(0)
  • 2021-02-05 19:51

    I'm using fauxconsole; I modified the css a bit so that it looks nicer but works very well.

    0 讨论(0)
  • 2021-02-05 19:55

    You can create a fake console:

    if (typeof console === "undefined")
        console = { log: function() { } };
    
    0 讨论(0)
提交回复
热议问题