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

  • Post author:
  • Post category:java


本文翻译自:

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 10



Visual 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!



%o



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