Chrome内置的JavaScript控制台可以显示颜色吗?

我想要错误在红色,警告在橙色和控制台。log在绿色。这可能吗?


当前回答

在Chrome & Firefox(+31)中,您可以在console.log消息中添加CSS:

console.log('%c我的天哪!', '背景:#222;颜色:# bada55 ');

同样适用于在同一命令中添加多个CSS。

参考文献

MDN:样式化控制台输出 Chrome:控制台API参考

其他回答

在Chrome & Firefox(+31)中,您可以在console.log消息中添加CSS:

console.log('%c我的天哪!', '背景:#222;颜色:# bada55 ');

同样适用于在同一命令中添加多个CSS。

参考文献

MDN:样式化控制台输出 Chrome:控制台API参考

实际上,我只是偶然发现了这个,好奇会发生什么,但你实际上可以使用bash着色标志来设置Chrome输出的颜色:

console.log('\x1b[36m Hello \x1b[34m Colored \x1b[35m World!');
console.log('\x1B[31mHello\x1B[34m World');
console.log('\x1b[43mHighlighted');

输出:

查看这个链接了解颜色标志的工作原理:https://misc.flogisoft.com/bash/tip_colors_and_formatting

基本上用\x1b或\x1b来代替\e。如。\x1b[31m及之后的所有文本将切换为新颜色。

虽然我还没有在其他浏览器中尝试过这个功能,但我认为值得一提。

默认情况下,很少有内置的控制台方法来显示警告、错误和正常控制台以及特定的图标和文本颜色。

console.log(“console.log”); console.warn(“console.warn”); console.error(“console.error”);

但如果您仍然想应用自己的样式,您可以使用%c与消息和CSS样式规则作为第二个参数。

Console.log ('%cconsole.log', 'color:绿色;'); console.warn(“% cconsole。警告','颜色:绿色;'); console.error(“% cconsole。错误','颜色:绿色;');

注意:在运行上述代码段时,请在浏览器控制台中检查结果,而不是代码段结果。

我写了一个npm模块,提供了通过的可能性:

自定义颜色-文本和背景; 前缀——帮助识别源代码,如[MyFunction] 类型——像警告、成功、信息和其他预定义的消息类型

https://www.npmjs.com/package/console-log-plus

输出(带有自定义前缀):

clp({
  type: 'ok',
  prefix: 'Okay',
  message: 'you bet'
});
clp({
  type: 'error',
  prefix: 'Ouch',
  message: 'you bet'
});
clp({
  type: 'warning',
  prefix: 'I told you',
  message: 'you bet'
});
clp({
  type: 'attention',
  prefix: 'Watch it!',
  message: 'you bet'
});
clp({
  type: 'success',
  prefix: 'Awesome!',
  message: 'you bet'
});
clp({
  type: 'info',
  prefix: 'FYI',
  message: 'you bet'
});
clp({
  type: 'default',
  prefix: 'No fun',
  message: 'you bet'
});

输出(不带自定义前缀):

输入:

clp({
  type: 'ok',
  message: 'you bet'
});
clp({
  type: 'error',
  message: 'you bet'
});
clp({
  type: 'warning',
  message: 'you bet'
});
clp({
  type: 'attention',
  message: 'you bet'
});
clp({
  type: 'success',
  message: 'you bet'
});
clp({
  type: 'info',
  message: 'you bet'
});
clp({
  type: 'default',
  message: 'you bet'
});

为了确保用户不会呈现无效的颜色,我还编写了一个颜色验证器。它将通过名称、十六进制、rgb、rgba、hsl或hsla值来验证颜色

您可以使用自定义样式表为调试器着色。你可以把这段代码放在C:\Documents and Settings<用户名>\Local Settings\Application Data\谷歌\Chrome\用户数据\Default\用户样式表\Custom.css(如果你在WinXP中),但是目录因操作系统不同而不同。

.console-error-level .console-message-text{
    color: red;
}

.console-warning-level .console-message-text {
    color: orange;
}

.console-log-level .console-message-text {
    color:green;
}