如何在Google Chrome JavaScript控制台中打印调试消息?

本文介绍了如何在Google Chrome的JavaScript控制台中打印调试消息,区分了控制台和调试器的不同,并提供了一些实用的打印方法,包括使用console.log(),以及针对Internet Explorer的解决方案。此外,还提到了在其他浏览器中可用的高级功能,如console.dump()和堆栈跟踪。
摘要由CSDN通过智能技术生成

本文翻译自:How do I print debug messages in the Google Chrome JavaScript Console?

How do I print debug messages in the Google Chrome JavaScript Console? 如何在Google Chrome JavaScript控制台中打印调试消息?

Please note that the JavaScript Console is not the same as the JavaScript Debugger; 请注意,JavaScript控制台与JavaScript调试器不同; they have different syntaxes AFAIK, so the print command in JavaScript Debugger will not work here. 它们具有不同的语法AFAIK,因此JavaScript调试器中的print命令在此处不起作用。 In the JavaScript Console, print() will send the parameter to the printer. 在JavaScript控制台中, print()会将参数发送到打印机。


#1楼

参考:https://stackoom.com/question/uhR/如何在Google-Chrome-JavaScript控制台中打印调试消息


#2楼

You could use console.log() if you have a debugged code in what programming software editor you have and you will see the output mostly likely the best editor for me (Google Chrome). 如果你在一个编程软件编辑器中有调试代码,你可以使用console.log() ,你会发现输出很可能是我最好的编辑器(谷歌浏览器)。 Just press F12 and press the Console tab. 只需按F12键,然后按“控制台”选项卡。 You will see the result. 你会看到结果。 Happy coding. 快乐的编码。 :) :)


#3楼

In addition to Delan Azabani's answer , I like to share my console.js , and I use for the same purpose. 除了Delan Azabani的回答 ,我喜欢分享我的console.js ,我也是出于同样的目的。 I create a noop console using an array of function names, what is in my opinion a very convenient way to do this, and I took care of Internet Explorer, which has a console.log function, but no console.debug : 我使用函数名称数组创建一个noop控制台,我认为这是一种非常方便的方法,我负责处理Internet Explorer,它有一个console.log函数,但是没有console.debug

// Create a noop console object if the browser doesn't provide one...
if (!window.console){
  window.console = {};
}

// Internet Explorer has a console that has a 'log' function, but no 'debug'. To make console.debug work in Internet Explorer,
// We just map the function (extend for info, etc. if needed)
else {
  if (!window.console.debug && typeof window.console.log !== 'undefined') {
    window.console.debug = window.console.log;
  }
}

// ... and create all functions we expect the console to have (taken from Firebug).
var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml",
    "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];

for (var i = 0; i < names.length; ++i){
  if(!window.console[names[i]]){
    window.console[names[i]] = function() {};
  }
}

#4楼

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. 而且,我真的不喜欢调试Internet Explorer,尽管Internet Explorer 10Visual Studio 2012等有了很大的改进。

So, I've overridden the console object itself... I've added a __localhost flag that only allows console statements when on localhost. 所以,我已经重写了控制台对象本身...我添加了一个__localhost标志,只允许在localhost上使用控制台语句。 I also added console.() functions to Internet Explorer (that displays an alert() instead). 我还在Internet Explorer中添加了console。()函数(显示了一个alert())。

// Console extensions...
(function() {
    var __localhost = (document.location.host === "localhost"),
        __allow_examine = true;

    if (!console) {
        console = {};
    }

    console.__log = console.log;
    console.log = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__log === "function") {
                console.__log(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__info = console.info;
    console.info = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__info === "function") {
                console.__info(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__warn = console.warn;
    console.warn = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__warn === "function") {
                console.__warn(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__error = console.error;
    console.error = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__error === "function") {
                console.__error(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg);
            }
        }
    };

    console.__group = console.group;
    console.group = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__group === "function") {
                console.__group(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert("group:\r\n" + msg + "{");
            }
        }
    };

    console.__groupEnd = console.groupEnd;
    console.groupEnd = function() {
        if (__localhost) {
            if (typeof console !== "undefined" && typeof console.__groupEnd === "function") {
                console.__groupEnd(arguments);
            } else {
                var i, msg = "";
                for (i = 0; i < arguments.length; ++i) {
                    msg += arguments[i] + "\r\n";
                }
                alert(msg + "\r\n}");
            }
        }
    };

    /// <summary>
    /// Clever way to leave hundreds of debug output messages in the code,
    /// but not see _everything_ when you only want to see _some_ of the
    /// debugging messages.
    /// </summary>
    /// <remarks>
    /// To enable __examine_() statements for sections/groups of code, type the
    /// following in your browser's console:
    ///       top.__examine_ABC = true;
    /// This will enable only the console.examine("ABC", ... ) statements
    /// in the code.
    /// </remarks>
    console.examine = function() {
        if (!__allow_examine) {
            return;
        }
        if (arguments.length > 0) {
            var obj = top["__examine_" + arguments[0]];
            if (obj && obj === true) {
                console.log(arguments.splice(0, 1));
            }
        }
    };
})();

Example use: 使用示例:

    console.log("hello");

Chrome/Firefox: 镀铬/火狐:

    prints hello in the console window.

Internet Explorer: IE浏览器:

    displays an alert with 'hello'.

For those who look closely at the code, you'll discover the console.examine() function. 对于仔细查看代码的人,您将发现console.examine()函数。 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: 例如,我会在一些已发布的代码中留下以下行:

    function doSomething(arg1) {
        // ...
        console.examine("someLabel", arg1);
        // ...
    }

And then from the released product, type the following into the console (or address bar prefixed with 'javascript:'): 然后从发布的产品中,在控制台(或带有'javascript:'前缀的地址栏)中键入以下内容:

    top.__examine_someLabel = true;

Then, I will see all of the logged console.examine() statements. 然后,我将看到所有已记录的console.examine()语句。 It's been a fantastic help many times over. 这是一次很棒的帮助。


#5楼

Simple Internet Explorer 7 and below shim that preserves line numbering for other browsers: 简单的Internet Explorer 7及以下垫片 ,可保留其他浏览器的行号:

/* Console shim */
(function () {
    var f = function () {};
    if (!window.console) {
        window.console = {
            log:f, info:f, warn:f, debug:f, error:f
        };
    }
}());

#6楼

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. 这是一个神奇的%o转储可点击和深度可浏览的JavaScript对象内容。 %s was shown just for a record. %s只是为了纪录。

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 !). 这给出了类似Java的堆栈跟踪到new Error()调用(包括文件路径和行号 !)。

Both %o and new Error().stack are available in Chrome and Firefox! %onew Error().stack都可以在Chrome和Firefox中使用!

Also for stack traces in Firefox use: 对于Firefox中的堆栈跟踪,还使用:

console.trace();

As https://developer.mozilla.org/en-US/docs/Web/API/console says. 正如https://developer.mozilla.org/en-US/docs/Web/API/console所说。

Happy hacking! 快乐的黑客!

UPDATE : Some libraries are written by bad people which redefine the console object for their own purposes. 更新 :一些库是由坏人编写的,它们为了自己的目的重新定义console对象。 To restore the original browser console after loading library, use: 要在加载库后还原原始浏览器console ,请使用:

delete console.log;
delete console.warn;
....

See Stack Overflow question Restoring console.log() . 请参阅堆栈溢出问题恢复console.log()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值