【问题标题】:How do I print debug messages in the Google Chrome JavaScript Console?如何在 Google Chrome JavaScript 控制台中打印调试消息?
【发布时间】:2010-09-18 02:13:09
【问题描述】:

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

请注意,JavaScript 控制台与 JavaScript 调试器不同;它们有不同的语法 AFAIK,所以 JavaScript 调试器中的 print 命令在这里不起作用。在 JavaScript 控制台中,print() 会将参数发送到打印机。

【问题讨论】:

    标签: javascript console debugging google-chrome


    【解决方案1】:

    从浏览器地址栏执行以下代码:

    javascript: 控制台.log(2);

    成功将消息打印到 Google Chrome 中的“JavaScript 控制台”。

    【讨论】:

    • 刚刚意识到,console.log() 非常适合 js 调试......我在实践中经常忘记使用它。
    • 这些“输出”之一可以持续多久?顺便顶一下,这真的很有帮助
    • @dbrin 这对于开发来说很好,但是任何console.log() 代码都应该在部署之前从生产代码中删除。
    • @Sebas Console.Log's 应该在部署之前从生产代码中删除,因为如果没有,这些消息将记录到用户的 JavaScript 控制台。虽然他们不太可能看到它,但它占用了他们设备上的内存空间。此外,根据日志的内容,您可能会告诉人们如何破解/逆向工程您的应用程序。
    【解决方案2】:

    改进 Andru 的想法,您可以编写一个脚本来创建控制台函数(如果它们不存在):

    if (!window.console) console = {};
    console.log = console.log || function(){};
    console.warn = console.warn || function(){};
    console.error = console.error || function(){};
    console.info = console.info || function(){};
    

    然后,使用以下任何一种:

    console.log(...);
    console.error(...);
    console.info(...);
    console.warn(...);
    

    这些函数将记录不同类型的项目(可以根据日志、信息、错误或警告进行过滤),并且在控制台不可用时不会导致错误。这些函数将在 Firebug 和 Chrome 控制台中运行。

    【讨论】:

    • 谢谢。如果您运行一次“if”,例如if (!window.console) {,然后将所有内容放在括号内,代码会不会更紧凑?现在你正在评估相同的东西四次。
    • 不,b/c 仅具有 window.console 并不能保证您将拥有 window.console.log 或 .warn &c
    • 请小心,因为如果此脚本与页面一起加载并且控制台窗口未打开,它将创建“虚拟”控制台,如果您打开控制台,则会阻止真正的控制台工作 在页面加载之后。 (至少在旧版本的 firefox/firebug 和 chrome 中是这种情况)
    • 我对此有补充,见下方my answer
    • 不,这将不会使 chrome 中止并出现 TypeError。上面的链接问题是关于用 this 调用的。上面的代码没有这样做,并且在 Chrome 中可以正常工作
    【解决方案3】:

    只需添加一个很多开发人员都错过的很酷的功能:

    console.log("this is %o, event is %o, host is %s", this, e, location.host);
    

    这是神奇的%o 转储JavaScript 对象的可点击和可深度浏览 内容。 %s 仅用于记录。

    这也很酷:

    console.log("%s", new Error().stack);
    

    这提供了一个类似于 Java 的堆栈跟踪到 new Error() 调用点(包括文件路径和行号!)。

    %onew Error().stack 在 Chrome 和 Firefox 中都可用!

    也用于 Firefox 中的堆栈跟踪:

    console.trace();
    

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

    黑客愉快!

    更新:一些库是由坏人编写的,他们为了自己的目的重新定义了console 对象。要在加载库后恢复原始浏览器console,请使用:

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

    查看堆栈溢出问题Restoring console.log()

    【讨论】:

    【解决方案4】:

    只是一个快速警告 - 如果您想在 Internet Explorer 中进行测试而不删除所有 console.log(),则需要使用 Firebug Lite 否则您会收到一些不太友好的错误。

    (或创建您自己的 console.log(),它只返回 false。)

    【讨论】:

    • 我避免像这样的跨浏览器错误:if (console) console.log()
    • 如果您在 IE (F12) 中打开开发者工具,console 对象将被创建并存在,直到您关闭该浏览器实例。
    【解决方案5】:

    这是一个检查控制台是否可用的简短脚本。如果不是,它会尝试加载 Firebug,如果 Firebug 不可用,它会加载 Firebug Lite。现在您可以在任何浏览器中使用console.log。享受吧!

    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.
    }
    

    【讨论】:

      【解决方案6】:

      除了Delan Azabani's answer,我还喜欢分享我的console.js,我也是出于同样的目的。我使用一组函数名称创建了一个 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() {};
        }
      }
      

      【讨论】:

        【解决方案7】:

        或者使用这个功能:

        function log(message){
            if (typeof console == "object") {
                console.log(message);
            }
        }
        

        【讨论】:

        • console.constructor === Object &amp;&amp; (log = m =&gt; console.log(m))
        【解决方案8】:

        这是我的控制台包装类。它也给了我范围输出,让生活更轻松。注意localConsole.debug.call() 的使用,以便localConsole.debug 在调用类的范围内运行,提供对其toString 方法的访问。

        localConsole = {
        
            info: function(caller, msg, args) {
                if ( window.console && window.console.info ) {
                    var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
                    if (args) {
                        params = params.concat(args);
                    }
                    console.info.apply(console, params);
                }
            },
        
            debug: function(caller, msg, args) {
                if ( window.console && window.console.debug ) {
                    var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
                    if (args) {
                        params = params.concat(args);
                    }
                    console.debug.apply(console, params);
                }
            }
        };
        
        someClass = {
        
            toString: function(){
                return 'In scope of someClass';
            },
        
            someFunc: function() {
        
                myObj = {
                    dr: 'zeus',
                    cat: 'hat'
                };
        
                localConsole.debug.call(this, 'someFunc', 'myObj: ', myObj);
            }
        };
        
        someClass.someFunc();
        

        这会在Firebug 中给出类似的输出:

        In scope of someClass.someFunc(), myObj: Object { dr="zeus", more...}
        

        或铬:

        In scope of someClass.someFunc(), obj:
        Object
        cat: "hat"
        dr: "zeus"
        __proto__: Object
        

        【讨论】:

          【解决方案9】:

          我个人用这个,和tarek11011的差不多:

          // Use a less-common namespace than just 'log'
          function myLog(msg)
          {
              // Attempt to send a message to the console
              try
              {
                  console.log(msg);
              }
              // Fail gracefully if it does not exist
              catch(e){}
          }
          

          主要的一点是,除了将console.log() 直接粘贴到您的 JavaScript 代码中之外,至少有一些记录实践是一个好主意,因为如果您忘记了它,并且它在生产站点上,它可能会破坏该页面的所有 JavaScript 代码。

          【讨论】:

          • 为什么不if(windows.console) console.log(msg)
          • window.console 你的意思是。唯一有用的尝试是如果抛出错误(如果 console.log 不是函数),因为控制台被重新定义。做window.console &amp;&amp; window.console.log instanceof Function 会更有用。
          【解决方案10】:

          如果您在所拥有的编程软件编辑器中有调试过的代码,您可以使用console.log(),并且您会看到输出很可能是最适合我的编辑器(Google Chrome)。只需按 F12 并按控制台选项卡。你会看到结果。快乐编码。 :)

          【讨论】:

            【解决方案11】:

            我在开发人员检查他们的 console.() 语句时遇到了很多问题。而且,我真的不喜欢调试 Internet Explorer,尽管 Internet Explorer 10Visual Studio 2012 等有了惊人的改进。

            所以,我已经覆盖了控制台对象本身...我添加了一个 __localhost 标志,它只允许在 localhost 上使用控制台语句。我还在 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));
                        }
                    }
                };
            })();
            

            使用示例:

                console.log("hello");
            

            Chrome/Firefox:

                prints hello in the console window.
            

            Internet Explorer:

                displays an alert with 'hello'.
            

            对于那些仔细查看代码的人,您会发现 console.examine() 函数。我是在几年前创建的,以便我可以在产品周围的某些区域保留调试代码,以帮助解决QA/customer 问题。例如,我会在一些已发布的代码中保留以下行:

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

            然后从已发布的产品中,在控制台(或以'javascript:'为前缀的地址栏)中键入以下内容:

                top.__examine_someLabel = true;
            

            然后,我将看到所有记录的 console.examine() 语句。多次提供了出色的帮助。

            【讨论】:

            • 感谢这个绝妙的主意。非常鼓舞人心。从您的检查功能中,我不知不觉地想到了调试 php 的范围的想法。 mydebug_on('somescope')、mydebug('somescope',$data) 等。现在我可以打开/关闭主题选择性调试和 php 代码日志记录。就像常规的 linux 程序一样,它可以登录标准的常规详细等风格。确实是个好主意!
            【解决方案12】:

            简单的Internet Explorer 7 及以下shim 为其他浏览器保留行号:

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

            【讨论】:

              【解决方案13】:
              console.debug("");
              

              使用此方法在控制台中以亮蓝色打印出文本。

              【讨论】:

                【解决方案14】:

                进一步改进 Delan 和 Andru 的想法(这就是为什么这个答案是经过编辑的版本); console.log 可能存在而其他函数可能不存在,因此将默认映射到与 console.log 相同的函数....

                如果控制台函数不存在,您可以编写一个脚本来创建它们:

                if (!window.console) console = {};
                console.log = console.log || function(){};
                console.warn = console.warn || console.log;  // defaults to log
                console.error = console.error || console.log; // defaults to log
                console.info = console.info || console.log; // defaults to log
                

                然后,使用以下任何一种:

                console.log(...);
                console.error(...);
                console.info(...);
                console.warn(...);
                

                这些函数将记录不同类型的项目(可以根据日志、信息、错误或警告进行过滤),并且在控制台不可用时不会导致错误。这些函数将在 Firebug 和 Chrome 控制台中运行。

                【讨论】:

                  【解决方案15】:

                  尽管这个问题很老,并且有很好的答案,但我想提供有关其他日志记录功能的更新。

                  您也可以分组打印:

                  console.group("Main");
                  console.group("Feature 1");
                  console.log("Enabled:", true);
                  console.log("Public:", true);
                  console.groupEnd();
                  console.group("Feature 2");
                  console.log("Enabled:", false);
                  console.warn("Error: Requires auth");
                  console.groupEnd();
                  

                  哪些打印:

                  根据this page,所有主要浏览器都支持此功能:

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2017-07-08
                    • 1970-01-01
                    相关资源
                    最近更新 更多