Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way of detecting whether a browsers console is able to render colors?

Tags:

Is there a way of checking to see if a browser is capable of using console colors without sniffing?

console.log('%c Oh my heavens! ', 'background: #222; color: #bada55'); 

For example that in chrome 26+ and firebug will print colored output.

like image 227
lededje Avatar asked May 10 '13 14:05

lededje


2 Answers

This is one of these few cases where browser version detection seems the valid way to go. To minimize the dangers of this approach make sure to use a blacklist rather than a whitelist, no matter how unintuitive this might feel right now (to make sure you don't leave out new future browser as happened with a lot of old netscape focused code). I am aware that this isn't the answer you wanted to hear, but as console.log is a native function and it's effect can in no way be observed, so as far as I can see the only option is to do browser version detection.

like image 54
David Mulder Avatar answered Oct 29 '22 00:10

David Mulder


I wrote Console.js https://github.com/icodeforlove/Console.js to allow us to do this a bit easier

Console.styles.register({   red: 'color: red',   underline: 'text-decoration: underline',   bold: 'font-weight: bold' }); 

then you can just do this

console.log('red text '.red + 'red underlined text'.red.underline + 'red bold text'.red.bold); 

it will gracefully degrade like this

console.js example

like image 41
Chad Scira Avatar answered Oct 29 '22 00:10

Chad Scira