ChatGPT解决这个技术问题 Extra ChatGPT

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

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

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


S
Sergey Ilinsky

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

javascript: console.log(2);

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


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

改进 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 而中止。上面的链接问题是关于用这个打电话的。上面的代码没有这样做,并且在 Chrome 中可以正常工作
C
Community

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

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

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

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


我刚刚发现的另一个:console.dir developer.mozilla.org/en-US/docs/Web/API/console.dir
P
Peter Mortensen

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

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


我避免像这样的跨浏览器错误: if (console) console.log()
如果您在 IE (F12) 中打开开发人员工具,则会创建 console 对象并一直存在,直到您关闭该浏览器实例。
P
Peter Mortensen

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

C
Community

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

P
Peter Mortensen

或使用此功能:

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

console.constructor === Object && (log = m => console.log(m))
P
Peter Mortensen

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

P
Peter Mortensen

我个人使用这个,它类似于 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 && window.console.log instanceof Function 会更有用。
P
Peter Mortensen

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


P
Peter Mortensen

我在开发人员检查他们的 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");

铬/火狐:

    prints hello in the console window.

IE浏览器:

    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 程序一样,它可以登录标准的常规详细等风格。真是个好主意!
P
Peter Mortensen

为其他浏览器保留行号的简单 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
        };
    }
}());

N
Nicholas Smith
console.debug("");

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

https://i.stack.imgur.com/KCjUx.png


v
vogomatix

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


D
Daniel

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

您还可以使用组打印:

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

哪个打印:

https://i.stack.imgur.com/5TqdF.png

https://i.stack.imgur.com/eOjxc.png