How do I print debug messages in the Google Chrome JavaScript Console?
Please note that the JavaScript Console is not the same as the JavaScript Debugger; they have different syntaxes AFAIK, so the print command in JavaScript Debugger will not work here. In the JavaScript Console, print()
will send the parameter to the printer.
Executing following code from the browser address bar:
successfully prints message to the "JavaScript Console" in Google Chrome.
Personally I use this, which is similar to tarek11011's:
The main point is that it's a good idea to at least have some practice of logging other than just sticking
console.log()
right into your JavaScript code, because if you forget about it, and it's on a production site, it can potentially break all of the JavaScript code for that page.Using this method prints out the text in a bright blue color in the console.
Here's my console wrapper class. It gives me scope output as well to make life easier. Note the use of
localConsole.debug.call()
so thatlocalConsole.debug
runs in the scope of the calling class, providing access to itstoString
method.This gives output like so in Firebug:
Or Chrome:
I've had a lot of issues with developers checking in their console.() statements. And, I really don't like debugging Internet Explorer, despite the fantastic improvements of Internet Explorer 10 and Visual Studio 2012, etc.
So, I've overridden the console object itself... I've added a __localhost flag that only allows console statements when on localhost. I also added console.() functions to Internet Explorer (that displays an alert() instead).
Example use:
Chrome/Firefox:
Internet Explorer:
For those who look closely at the code, you'll discover the console.examine() function. I created this years ago so that I can leave debug code in certain areas around the product to help troubleshoot QA/customer issues. For instance, I would leave the following line in some released code:
And then from the released product, type the following into the console (or address bar prefixed with 'javascript:'):
Then, I will see all of the logged console.examine() statements. It's been a fantastic help many times over.
Just add a cool feature which a lot of developers miss:
This is the magical
%o
dump clickable and deep-browsable content of a JavaScript object.%s
was shown just for a record.Also this is cool too:
Which gives a Java-like stack trace to the point of the
new Error()
invocation (including path to file and line number!).Both
%o
andnew Error().stack
are available in Chrome and Firefox!Also for stack traces in Firefox use:
As https://developer.mozilla.org/en-US/docs/Web/API/console says.
Happy hacking!
UPDATE: Some libraries are written by bad people which redefine the
console
object for their own purposes. To restore the original browserconsole
after loading library, use:See Stack Overflow question Restoring console.log().