繁体   English   中英

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

[英]How do I print debug messages in the Google Chrome JavaScript Console?

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

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

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

javascript: console.log(2);

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

改进 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 控制台中工作。

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

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

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

这也很酷:

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

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

%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;
....

请参阅堆栈溢出问题恢复 console.log()

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

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

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

除了Delan Azabani 的回答之外,我还喜欢分享我的console.js ,并且用于相同的目的。 我使用一组函数名称创建了一个 noop 控制台,在我看来这是一种非常方便的方法,并且我处理了具有console.log函数但没有console.debug的 Internet Explorer:

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

或者使用这个函数:

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

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

我个人使用这个,类似于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 代码。

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

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

所以,我已经覆盖了控制台对象本身......我添加了一个 __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() 语句。 多次提供了极大的帮助。

为其他浏览器保留行编号的简单Internet Explorer 7及以下垫片

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

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

在此处输入图片说明

进一步改进 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 控制台中工作。

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

您还可以使用组进行打印:

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

哪个打印:

在此处输入图片说明

根据 此页面,所有主要浏览器都支持 此功能 在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM