“控制台”是 Internet Explorer 的未定义错误

我正在使用Firebug,并有一些语句,例如:

console.log("...");

在我的页面中。在IE8(也可能是早期版本)中,我收到脚本错误,说“控制台”未定义。我试着把它放在我的页面顶部:

<script type="text/javascript">
    if (!console) console = {log: function() {}};
</script>

我仍然得到错误。有什么方法可以摆脱错误吗?


答案 1

尝试

if (!window.console) console = ...

不能直接引用未定义的变量。但是,所有全局变量都是与全局上下文同名的属性(在浏览器的情况下),并且访问未定义的属性是可以的。window

或者,如果您想避免魔术变量,请使用,请参阅@Tim Down的答案if (typeof console === 'undefined') console = ...window


答案 2

将以下内容粘贴到 JavaScript 的顶部(在使用控制台之前):

/**
 * Protect window.console method calls, e.g. console is not defined on IE
 * unless dev tools are open, and IE doesn't define console.debug
 * 
 * Chrome 41.0.2272.118: debug,error,info,log,warn,dir,dirxml,table,trace,assert,count,markTimeline,profile,profileEnd,time,timeEnd,timeStamp,timeline,timelineEnd,group,groupCollapsed,groupEnd,clear
 * Firefox 37.0.1: log,info,warn,error,exception,debug,table,trace,dir,group,groupCollapsed,groupEnd,time,timeEnd,profile,profileEnd,assert,count
 * Internet Explorer 11: select,log,info,warn,error,debug,assert,time,timeEnd,timeStamp,group,groupCollapsed,groupEnd,trace,clear,dir,dirxml,count,countReset,cd
 * Safari 6.2.4: debug,error,log,info,warn,clear,dir,dirxml,table,trace,assert,count,profile,profileEnd,time,timeEnd,timeStamp,group,groupCollapsed,groupEnd
 * Opera 28.0.1750.48: debug,error,info,log,warn,dir,dirxml,table,trace,assert,count,markTimeline,profile,profileEnd,time,timeEnd,timeStamp,timeline,timelineEnd,group,groupCollapsed,groupEnd,clear
 */
(function() {
  // Union of Chrome, Firefox, IE, Opera, and Safari console methods
  var methods = ["assert", "cd", "clear", "count", "countReset",
    "debug", "dir", "dirxml", "error", "exception", "group", "groupCollapsed",
    "groupEnd", "info", "log", "markTimeline", "profile", "profileEnd",
    "select", "table", "time", "timeEnd", "timeStamp", "timeline",
    "timelineEnd", "trace", "warn"];
  var length = methods.length;
  var console = (window.console = window.console || {});
  var method;
  var noop = function() {};
  while (length--) {
    method = methods[length];
    // define undefined methods as noops to prevent errors
    if (!console[method])
      console[method] = noop;
  }
})();

函数闭包包装器的作用域为不定义任何变量。这可以防止未定义和未定义(以及其他缺少的方法)。consoleconsole.debug

编辑:我注意到HTML5 Boilerplate在其js /plugins.js文件中使用了类似的代码,如果你正在寻找一个(可能)保持最新的解决方案。