I 'waddled' by the Console in Chrome on Facebook today.
Surprisingly I got this message in the console.
Now my question is:
How is this possible?
I know that there are a few 'exploit' methods for the console, but how can you make such font formatting in the console? (and is it console.log?)
5 Answers
Yes, you can format the console.log()
with something like this:
console.log("%cExtra Large Yellow Text with Red Background", "background: red; color: yellow; font-size: x-large");
Note the %c
preceding the text in the first argument and the style specifications in the second argument. The text will look like your example.
See Google's "Styling Console Output with CSS" or FireBug's Console Documentation for more details.
The documentation links also include some other neat tricks like including object links in a console log as well.
-
You might want to check that a compatible browser is in use before trying to use format strings in
console.log
, since older browsers might stop your script with an exception. caniuse says it was introduced in Firefox 9 and Edge 79; Chrome started supporting it evidently some time before Chrome 83 but we don't know exactly when. Jun 24, 2020 at 13:58
Try this:
console.log("%cThis will be formatted with blue text", "color: blue");
Quoting the docs,
You use the %c format specifier to apply custom CSS rules to any string you write to the Console with console.log() or related methods.
-
10Hi downvoter, any comments to add? - it's hard to improve an answer (that you think is not good) when you don't leave comments explaining yourself. :)– blurfusJul 26, 2018 at 18:15
You can also format substrings.
var red = 'color:red';
var blue = 'color:blue';
console.log('%cHello %cWorld %cfoo %cbar', red, blue, red, blue);
-
4Note that it is only possible to style within the first argument of
console.log
and the styles must follow immediately.– QwertyApr 6, 2018 at 12:09
From Google's website: site
console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large");
Just extending other answers and you can reuse the existing css style of selector, class, element. Try this in SO console window.
const customLog = (message, cssSelector) =>
console.log(
`%c${message}`,
Object.entries(getComputedStyle(document.querySelector(cssSelector)))
.map(([k, v]) => `${k}:${v}`)
.join(";")
);
customLog("Hello StackOverflow", "#question-header > div > a");
customLog("Hello StackOverflow", "strong");
customLog("Hello StackOverflow", "a");