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

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

有帮助吗?

解决方案

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

javascript: console.log(2);

成功将消息打印到“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);

这是JavaScript对象的神奇%o dump 可点击且可深入浏览的内容。 %s 仅用于记录。

这也很酷:

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

这给出了类似Java的堆栈跟踪到 new Error()调用(包括文件路径和行号!)。

Chrome和Firefox都提供%o new Error()。stack

对于Firefox中的堆栈跟踪,请使用:

console.trace();

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

快乐的黑客攻击!

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

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

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

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

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

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

或使用此功能:

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...}

或Chrome:

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(),并且您会看到输出可能是我最好的编辑器(Google Chrome)。只需按 F12 并按“控制台”选项卡。你会看到结果。快乐的编码。 :)

我在开发人员检查他们的控制台时遇到了很多问题。()语句。而且,我真的不喜欢调试Internet Explorer,尽管 Internet Explorer&nbsp; Explorer 10 Visual&nbsp; Studio&nbsp; 2012 等。

所以,我已经重写了控制台对象本身......我添加了一个__localhost标志,只允许在localhost上使用控制台语句。我还将控制台。()函数添加到Internet&nbsp;资源管理器(显示警报())。

// 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.

Internet Explorer:

    displays an alert with 'hello'.

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

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

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

    top.__examine_someLabel = true;

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

简单互联网浏览器&nbsp; 7 及以下 shim 保留其他浏览器的行号:

/* 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控制台。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top