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

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


当前回答

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

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

其他回答

这是我的控制台包装类。它还提供了范围输出,使工作更简单。注意使用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

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

javascript: console.log(2);

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

我在开发人员检入他们的控制台.()语句时遇到了很多问题。而且,我真的不喜欢调试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()语句。这已经帮了我很多次了。

下面是一个简短的脚本,用于检查控制台是否可用。如果没有,它会尝试加载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.
}

除了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() {};
  }
}