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

前端 未结 14 877
清酒与你
清酒与你 2020-11-27 08:54

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

14条回答
  •  北海茫月
    2020-11-27 09:29

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

提交回复
热议问题