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.
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.
Share Improve this question asked May 10, 2013 at 14:53 lededjelededje 1,8691 gold badge16 silver badges25 bronze badges 3- 1 Why you need to print colors in consol? it is only for debugging purpose – Chamika Sandamal Commented May 20, 2013 at 6:27
- 2 I am building a debugging tool in js... – lededje Commented May 20, 2013 at 12:54
- 4 Why does someone who only asks 'why do you need...' get a +1? I hate that question! Why is it relevant why someone needs something? – Stijn de Witt Commented Sep 15, 2016 at 18:46
2 Answers
Reset to default 11 +50This 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.
I wrote Console.js https://github./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