Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 476
Sean Anderson Avatar asked Oct 25 '11 16:10

Sean Anderson


2 Answers

You can create a fake console:

if (typeof console === "undefined")
    console = { log: function() { } };
like image 150
SLaks Avatar answered Sep 28 '22 09:09

SLaks


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);
like image 30
zzzzBov Avatar answered Sep 28 '22 08:09

zzzzBov