我如何打印调试消息在谷歌Chrome JavaScript控制台?

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


当前回答

我在开发人员检入他们的控制台.()语句时遇到了很多问题。而且,我真的不喜欢调试Internet Explorer,尽管Internet Explorer 10和Visual 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. inspect()函数。这是我在几年前创建的,这样我就可以在产品的某些区域留下调试代码,以帮助解决QA/客户问题。例如,我会在一些发布的代码中留下以下一行:

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

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

    top.__examine_someLabel = true;

然后,我将看到所有已记录的console. inspect()语句。这已经帮了我很多次了。

其他回答

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

只需要添加一个许多开发者忽略的功能:

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

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

这个也很酷:

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

它提供到新的Error()调用点的类似java的堆栈跟踪(包括文件路径和行号!)

%o和new Error()。堆栈可用在Chrome和Firefox!

在Firefox中也可以使用堆栈跟踪:

console.trace();

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

黑客快乐!

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

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

参见堆栈溢出问题恢复console.log()。

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

javascript: console.log(2);

成功打印消息到“JavaScript控制台”在谷歌Chrome浏览器。

除了Delan Azabani的回答,我还喜欢分享我的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() {};
  }
}

只是一个简短的警告——如果你想在不删除所有console.log()的情况下在Internet Explorer中测试,你需要使用Firebug Lite,否则你会得到一些不太友好的错误。

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