首页 文章

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

提问于
浏览
447

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

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

14 回答

  • 47

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

    javascript: console.log(2);
    

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

  • 14

    改进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控制台 .

  • 1

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

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

    这是JavaScript对象的神奇 %o 转储可点击和深度可浏览内容 . %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所说 .

    快乐的黑客!

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

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

    请参阅Stack Overflow问题Restoring console.log() .

  • 579

    只是一个快速警告 - 如果你想在Internet Explorer中测试而不删除所有console.log()'s, you' ll需要使用Firebug Lite或者你会得到一些不是特别友好的错误 .

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

  • 166

    这是一个简短的脚本,用于检查控制台是否可用 . 如果不是,则尝试加载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.
    }
    
  • 2

    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() {};
      }
    }
    
  • 17

    或者使用此功能:

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

    这是我的控制台包装类 . 它还为我提供了范围输出,使生活更轻松 . 请注意 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...}
    

    或Chrome:

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

    我个人使用这个,类似于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该页面的代码 .

  • 7

    你可以使用 console.log() ,如果你在一个编程软件编辑器中有一个调试过的代码,你会看到输出很可能是我最好的编辑器(谷歌浏览器) . 只需按F12,然后按“控制台”选项卡 . 你会看到结果 . 快乐的编码 . :)

  • 6

    我've had a lot of issues with developers checking in their console.() statements. And, I really don'喜欢调试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");
    

    镀铬/火狐:

    prints hello in the console window.
    

    IE浏览器:

    displays an alert with 'hello'.
    

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

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

    然后从发布的产品中,将以下内容输入控制台(或以“javascript:”为前缀的地址栏):

    top.__examine_someLabel = true;
    

    然后,我将看到所有已记录的console.examine()语句 . 这是一次很棒的帮助 .

  • 4

    简单的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
            };
        }
    }());
    
  • 4
    console.debug("");
    

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

    enter image description here

  • 3

    进一步改进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控制台 .

相关问题