Is there a way to log to console without breaking

2019-03-18 14:32发布

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 working when it hits console.log. This is a pain... it means I have to remove all the logging whenever I want to do a production build.

Aside from the obvious:

function DoSafeConsoleLog( parameters )
{
    if ( !$.browser.msie )
    {
         console.log( parameters ); 
    }
}

is there a good way to log javascript that is friendly to all major browsers?

EDIT:

Well, after looking at the duplicate post (oops) as well as considering the answers here, I've gotta side with just checking for the existence of console before calling. Even though I am loathe to have the extra markup, I would rather not step on the feet of future programmers who might want to use Firebug Lite to debug my code.

6条回答
爷的心禁止访问
2楼-- · 2019-03-18 14:42

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() {};
};
查看更多
爷、活的狠高调
3楼-- · 2019-03-18 14:46

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

查看更多
\"骚年 ilove
4楼-- · 2019-03-18 14:53

You can create a fake console:

if (typeof console === "undefined")
    console = { log: function() { } };
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-03-18 14:57

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);
查看更多
▲ chillily
6楼-- · 2019-03-18 14:57

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]-->
查看更多
手持菜刀,她持情操
7楼-- · 2019-03-18 14:59
function log(log){
  try{
     console.log( log); 
  }catch(err){}
}
查看更多
登录 后发表回答