How do I create formatted javascript console log messages

JavascriptHtmlGoogle ChromeWebkitExploit

Javascript Problem Overview


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?)

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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.

Source: https://developers.google.com/web/tools/chrome-devtools/console/console-write#styling_console_output_with_css

Solution 3 - Javascript

You can also format substrings.

var red = 'color:red';
var blue = 'color:blue';
console.log('%cHello %cWorld %cfoo %cbar', red, blue, red, blue);

enter image description here

Solution 4 - Javascript

From Google's website: site

console.log("%cThis will be formatted with large, blue text", "color: blue; font-size: x-large");

Solution 5 - Javascript

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");

enter image description here

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnders KjeldsenView Question on Stackoverflow
Solution 1 - JavascriptSmernView Answer on Stackoverflow
Solution 2 - JavascriptblurfusView Answer on Stackoverflow
Solution 3 - JavascriptKrzysztof BoduchView Answer on Stackoverflow
Solution 4 - JavascriptJonathanView Answer on Stackoverflow
Solution 5 - JavascriptSiva K VView Answer on Stackoverflow