11

我有以下内容:

console.log (a.time_ago() + ' ' + b.time_ago());

这在 FireFox 3 中被打破,这意味着当 FF 在 JS 中击中该行时,它不会再进一步​​了。奇怪的是,如果我打开 Firebug,它不会中断并继续正常运行。萤火虫如何防止这个问题?

我对这个感到困惑。关于为什么console.log会破坏firefox 3的任何想法,但如果firebug是打开的则不会?

谢谢

4

6 回答 6

30

这不仅仅是火狐。您的代码将停止在所有浏览器中运行(除了 Chrome 和 safari(在某些情况下),因为它们内置了 console.log() 及其开发人员工具。)

这是因为当您没有打开 firebug 时,没有定义对象“控制台”。你应该注意永远不要在你的代码中留下 console.log() 函数,否则它会在每个浏览器中中断。


我想补充一点,我有时会使用此功能:

function log () {
    if (typeof console == 'undefined') {
        return;
    }
    console.log.apply(console, arguments);
}

然后你可以简单地调用:

log(somevar, anothervar);

它的工作方式与console.log相同,但如果未加载firebug(并且键入更短:P),则不会失败

干杯

于 2011-02-10T22:16:00.257 回答
4

如果该萤火虫已关闭,我将覆盖控制台对象。因此,您可以实现后备功能...

console = console || { log : function() {
// place your logging code here, if firebug is closed
}, debug : function() {
// place your debug code here, if firebug is closed
} /*, [ and so on .. ] */ };

问候,

迪沃尔

于 2011-02-10T22:35:51.070 回答
2

在 FireFox 中,如果您调用控制台时控制台未打开,则会引发 JavaScript 错误。

我将所有console.log 包装在一个包装器中以检查控制台-您可以将检查包装在控制台调用周围,也可以使用不同的名称来别名控制台。

别名

/* konsole is a safe wrapper for the Firebug console. */
var konsole = {
  log: function(args){},
  dir: function(args){},
  debug: function(args){},
  info: function(args){},
  warn: function(args){},
  error: function(args){}
};
// Remove below here when in production
if (typeof window.console != 'undefined' && typeof window.console.log == 'function') {
  konsole = window.console;
}
konsole.log('testing debugging');
konsole.error('throw an error message to the console');

检查控制台

if (typeof window.console != 'undefined' && typeof window.console.log == 'function') {
  console.log('testing debugging');
  console.error('throw an error message to the console');
}
于 2011-02-10T22:20:31.640 回答
1

我总是if (console)检查以确保控制台确实存在。如果萤火虫没有打开,就好像你正在作用于一个空对象,因此它为什么会中断。

于 2011-02-10T22:16:16.523 回答
1

Firefox 没有控制台对象。Firebug 增加了一个。

简单的解决方法是打开 firebug 进行开发并删除 console.log 语句进行部署。

您还可以制作自定义日志功能,例如

function log (msg)
{
  if(console)
  {
    console.log(msg);
  }
}

仅当控制台存在时才会记录

于 2011-02-10T22:18:07.660 回答
0

为了防止 Firefox 3.0可靠地抱怨,请使用以下...

if ('console' in window) {}
于 2014-07-06T22:38:12.110 回答