How do I print debug messages in the Google Chrome JavaScript Console?
Improving on Andru's idea, you can write a script which creates console functions if they don't exist:
if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || function(){};
console.error = console.error || function(){};
console.info = console.info || function(){};
Then, use any of the following:
console.log(...);
console.error(...);
console.info(...);
console.warn(...);
These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.
Just add a cool feature which a lot of developers miss:
console.log("this is %o, event is %o, host is %s", this, e, location.host);
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:
console.log("%s", new Error().stack);
Which gives a Java-like stack trace to the point of the new Error()
invocation (including path to file and line number!).
Both %o
and new Error().stack
are available in Chrome and Firefox!
Also for stack traces in Firefox use:
console.trace();
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 browser console
after loading library, use:
delete console.log;
delete console.warn;
....
See Stack Overflow question Restoring console.log().
Executing following code from the browser address bar:
javascript: console.log(2);
successfully prints message to the "JavaScript Console" in Google Chrome.