Last Updated: February 25, 2016
·
232
· rabidaudio

Testing for colored console.log support

If you weren't aware, many browser consoles will let you style the log output. For modern browsers, you can start your message with %c and pass CSS styling as the second argument:

console.log('%cHello, Console!', 'font-size: large;color: red; font-style: italic;');

This works in Firebug, Firefox >= 31 without Firebug, and webkit since about 10/10/2012.

You can get pretty fancy with libraries like this one:
http://icodeforlove.github.io/Console.js/

However, 5kb minifed for something that doesn't add real value to a production site is kinda expensive. So if you just want to enable it for Chrome and Firefox, here's 183 bytes:

console.clog=(function(m,s){return (s&&(parseInt((navigator.userAgent.match(/Firefox\/(.*)\b/)||[0,0])[1])>=31||!!window.chrome) ? this.log('%c'+m,s) : this.log(m));}).bind(console);

If you don't want to monkeypatch console, just change the name (e.g. clog=...).

Cheers,

cjk