32

When outputting messages into the console, the source is also displayed (in Chrome Developer Tools it's on the right):

console.log("Foo");                         //Source
Foo                               test.js:1 //Output

However, on some sites, messages are displayed without the source being displayed, such as on Facebook:

Console screenshot on Facebook.com

Having a look on the Chrome Console API Reference there are examples across a ton of different outputs but all of them have the source displayed.

How can I hide the source (.js page and line number) of console outputs?


Edit: Just for clarification, this is not a duplicate of How does Facebook disable the browser's integrated Developer Tools? as that question answers how the console disables standard user input (and its answers explain how it works). I am specifically asking about the aesthetic of not displaying the source file and line.

Community
  • 1
  • 1
Ben
  • 8,894
  • 7
  • 44
  • 80
  • Out of interest, on what URL do you see the console output you've shown in your image? I don't see that when I visit facebook.com in Chrome. – ED-209 Jan 13 '16 at 09:55
  • You must be logged in to see that message. – Ben Jan 13 '16 at 09:56

2 Answers2

37

They are using setTimeout to detach from the source:

setTimeout(console.log.bind(console, '\n%c' + s[0], s[1]));
Oliver Salzburg
  • 21,652
  • 20
  • 93
  • 138
  • 2
    What does `s[0]` and `s[1]` reference? The message and the CSS style, I presume? – Ben Jan 13 '16 at 09:47
  • @OliverSalzburg Thanks a lot. It worked perfectly. But I am having a hard time to understand how it works. Can you explain how does it works? – Niroj Shrestha Jul 07 '16 at 07:33
  • 4
    @NirojShrestha Think of it like this: You're passing `setTimeout` a function, which is it supposed to execute later. So it places the function that was passed to it in a virtual space somewhere in memory and it loses the information of where it originated from. When the time comes, it will then execute that function, which has no line, because it just resides somewhere in memory. At least that's my take on things, I don't have a deep understanding of how the code is executed internally. – Oliver Salzburg Jul 07 '16 at 07:50
  • @DerHochstapler but why `setTimeout(() => console.log('hello world'));` show the trace? – legend80s Jan 09 '19 at 07:32
  • @legend80s Because fat-arrow functions are different – Oliver Salzburg Jan 10 '19 at 14:22
  • @DerHochstapler Uh, so what's the difference? – legend80s Feb 18 '19 at 02:05
  • why don't you just `setTimeout(console.log.bind(console, 'text'));` – Bouh Mar 17 '22 at 16:37
4

for those who are still looking for this, you can use something like

function consoleWithNoSource(...params) {
  setTimeout(console.log.bind(console, ...params));
}

consoleWithNoSource("Helloo....!")
Ameen Rashad
  • 514
  • 6
  • 17