How do I print debug messages in the Google Chrome JavaScript Console?

447,239

Solution 1

Executing following code from the browser address bar:

javascript: console.log(2);

successfully prints message to the "JavaScript Console" in Google Chrome.

Solution 2

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.

Solution 3

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().

Solution 4

Here is a short script which checks if the console is available. If it is not, it tries to load Firebug and if Firebug is not available it loads Firebug Lite. Now you can use console.log in any browser. Enjoy!

if (!window['console']) {

    // Enable console
    if (window['loadFirebugConsole']) {
        window.loadFirebugConsole();
    }
    else {
        // No console, use Firebug Lite
        var firebugLite = function(F, i, r, e, b, u, g, L, I, T, E) {
            if (F.getElementById(b))
                return;
            E = F[i+'NS']&&F.documentElement.namespaceURI;
            E = E ? F[i + 'NS'](E, 'script') : F[i]('script');
            E[r]('id', b);
            E[r]('src', I + g + T);
            E[r](b, u);
            (F[e]('head')[0] || F[e]('body')[0]).appendChild(E);
            E = new Image;
            E[r]('src', I + L);
        };
        firebugLite(
            document, 'createElement', 'setAttribute', 'getElementsByTagName',
            'FirebugLite', '4', 'firebug-lite.js',
            'releases/lite/latest/skin/xp/sprite.png',
            'https://getfirebug.com/', '#startOpened');
    }
}
else {
    // Console is already available, no action needed.
}

Solution 5

Just a quick warning - if you want to test in Internet Explorer without removing all console.log()'s, you'll need to use Firebug Lite or you'll get some not particularly friendly errors.

(Or create your own console.log() which just returns false.)

Share:
447,239
Tamas Czinege
Author by

Tamas Czinege

Software Developer

Updated on July 08, 2022

Comments

  • Tamas Czinege
    Tamas Czinege almost 2 years

    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.

  • Ish
    Ish almost 13 years
    Just realized, console.log() is awesome for js debugging ... I often forget using it in practice.
  • Dan Rosenstark
    Dan Rosenstark almost 13 years
    Thanks for that. Wouldn't the code be tighter if you ran the "if" once, like if (!window.console) { and then put everything inside brackets? Right now you're evaluating the same stuff four times.
  • Paul
    Paul almost 13 years
    No, b/c just having window.console doesn't guarantee that you'll have a window.console.log or .warn &c
  • cwd
    cwd over 12 years
    Just be careful because if this script is loaded with the page and the console window is not open, it will create the 'dummy' console which can prevent the real console from working if you open the console after the page is loaded. (at least this is the case in older versions of firefox/firebug and chrome)
  • Miles010
    Miles010 almost 12 years
    I avoid cross browser errors like such: if (console) console.log()
  • Tim Büthe
    Tim Büthe almost 12 years
    I have additions to this, see my answer below
  • JimmyMcHoover
    JimmyMcHoover over 11 years
    why not if(windows.console) console.log(msg)?
  • Aram Kocharyan
    Aram Kocharyan over 11 years
    window.console you mean. the only time the try would be useful is if an Error was thrown (if console.log wasn't a function) since console was redefined. Doing window.console && window.console.log instanceof Function would be more useful.
  • geira
    geira over 10 years
    This will make Chrome abort with a "TypeError: Illegal Invocation" error. See stackoverflow.com/questions/8159233/…
  • nbura
    nbura over 10 years
    How long can one of these "outputs" be? Upvote by the way, this was really helpful
  • dbrin
    dbrin over 10 years
    One other I just discovered: console.dir developer.mozilla.org/en-US/docs/Web/API/console.dir
  • Johan
    Johan over 10 years
    Thanks for this wonderful idea. Was quite inspiring. From your examine function, I unwittingly went on to the idea of scope for debugging php. mydebug_on('somescope'), mydebug('somescope',$data) etc. Now I can turn on/off subject selective debugging and logging for php code. And just like regular linux programs it can log in a standard regular verbose etc flavor. Quite a nice idea indeed!
  • Tim Büthe
    Tim Büthe over 10 years
    If you open the developer tools in IE (F12), the console object is created and exists till you close that browser instance.
  • Samuel MacLachlan
    Samuel MacLachlan over 9 years
    @dbrin this is fine for development, however any console.log() code should be removed from production code before deployment.
  • Samuel MacLachlan
    Samuel MacLachlan over 8 years
    @Sebas Console.Log's should be removed from production code before deployment because if not, these messages will be logging to your users' JavaScript console. Whilst they're unlikely to see it, it is taking up memory space on their device. Also, depending on the content of the Log, you're potentially telling people how to hack/reverse engineer your app.
  • gman
    gman about 8 years
    No, this will not make chrome abort with a TypeError. The linked question above is about calling with this. The code above doesn't do that and will work just fine in Chrome
  • vhs
    vhs almost 6 years
    console.constructor === Object && (log = m => console.log(m))