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

Tam*_*ege 459 javascript debugging console google-chrome

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

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

Ser*_*sky 592

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

javascript: console.log(2);

成功将消息打印到Google Chrome中的"JavaScript控制台".

  • 刚刚意识到,`console.log()`对于js调试很棒......我经常忘记在实践中使用它. (13认同)
  • @dbrin这适用于开发,但是在部署之前应该从生产代码中删除任何`console.log()`代码. (3认同)
  • 在2013年没有人应该这样做LOL :) (2认同)
  • 塞缪尔,也有工具! (2认同)
  • @Sebas`Console.Log`应该在部署之前从生产代码中删除,因为如果没有,这些消息将记录到用户的JavaScript控制台.虽然他们不太可能看到它,但它占用了设备上的内存空间.此外,根据日志的内容,您可能会告诉人们如何破解/反向设计您的应用程序. (2认同)

Del*_*ani 166

改进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(){};
Run Code Online (Sandbox Code Playgroud)

然后,使用以下任何一项:

console.log(...);
console.error(...);
console.info(...);
console.warn(...);
Run Code Online (Sandbox Code Playgroud)

这些函数将记录不同类型的项目(可以根据日志,信息,错误或警告进行过滤),并且在控制台不可用时不会导致错误.这些功能适用于Firebug和Chrome控制台.

  • 请注意,因为如果此脚本加载了页面并且控制台窗口未打开,它将创建"虚拟"控制台,如果在加载页面后打开控制台*,它可能会阻止真正的控制台工作.(至少在旧版本的firefox/firebug和chrome中就是这种情况) (18认同)

gav*_*koa 47

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

console.log("this is %o, event is %o, host is %s", this, e, location.host);
Run Code Online (Sandbox Code Playgroud)

这是JavaScript对象的神奇%o转储可点击和深度可浏览内容.%s只是为了记录而被展示.

这也很酷:

console.log("%s", new Error().stack);
Run Code Online (Sandbox Code Playgroud)

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

双方%onew Error().stack在Chrome和Firefox提供!

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

console.trace();
Run Code Online (Sandbox Code Playgroud)

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

快乐的黑客!

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

delete console.log;
delete console.warn;
....
Run Code Online (Sandbox Code Playgroud)

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

  • 我刚刚发现的另一个:console.dir https://developer.mozilla.org/en-US/docs/Web/API/console.dir (3认同)

And*_*dru 17

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

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

  • 我避免像这样的跨浏览器错误:if(console)console.log() (2认同)

小智 17

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


Tim*_*the 14

除了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() {};
  }
}
Run Code Online (Sandbox Code Playgroud)


Tar*_*ied 12

或者使用此功能:

function log(message){
    if (typeof console == "object") {
        console.log(message);
    }
}
Run Code Online (Sandbox Code Playgroud)


Bru*_*uce 7

这是我的控制台包装类.它还为我提供了范围输出,使生活更轻松.注意使用,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();
Run Code Online (Sandbox Code Playgroud)

这给出了Firebug中的输出:

In scope of someClass.someFunc(), myObj: Object { dr="zeus", more...}
Run Code Online (Sandbox Code Playgroud)

或Chrome:

In scope of someClass.someFunc(), obj:
Object
cat: "hat"
dr: "zeus"
__proto__: Object
Run Code Online (Sandbox Code Playgroud)


cwd*_*cwd 6

我个人使用这个,类似于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){}
}
Run Code Online (Sandbox Code Playgroud)

重点是,至少有一些日志记录的做法不仅仅是坚持console.log()使用JavaScript代码,这是一个好主意,因为如果你忘了它,并且它在生产站点上,它可能会破坏所有的JavaScript代码该页面.