Internet Explorer:“;控制台未定义”;错误

Internet Explorer: "console is not defined" Error

本文关键字:未定义 错误 控制台 Internet Explorer      更新时间:2023-09-26

我在编写的某些JavaScript中使用了console.log(),在Internet Explorer中引发了一个错误:console is not defined(在其他浏览器中运行良好)。

我已将其替换为:

if (console) console.log("...");

如果consoleundefined,我希望条件求值为false。呃,语句console.log不会被执行,也不应该抛出错误。

相反,会引发一个错误:console is not defined at character 4

这是IE漏洞吗?或者这种"如果"条件真的是非法的吗?这似乎很荒谬,因为如果if (console)是非法的,那么if (console==undefined)也应该是非法的。

您应该如何检查undefined变量?

其他答案为您提供了根本原因。然而,有一个比在调用console.* 之前使用if更好的解决方案

在包括任何使用控制台的脚本之前添加这个(一次):

//Ensures there will be no 'console is undefined' errors
window.console = window.console || (function(){
    var c = {}; c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile = c.clear = c.exception = c.trace = c.assert = function(s){};
    return c;
})();

这将只在"伪"控制台不存在的情况下创建它,这样"控制台未定义"错误就会消失,您不必每次都询问控制台是否存在。这样,您只需在任何地方调用console.log或任何控制台方法,就不会出现问题。

希望这能有所帮助。干杯

如果console本身根本不存在,它会抛出一个错误,因为您正在访问一个未定义的变量。就像if(abc) {}抛出错误一样。

由于console驻留在window中,并且window确实始终存在,因此这应该起作用:

if(window.console) ...

基本上,访问不存在的属性是免费的,并且不会引发错误(它只是计算为undefined,不满足if条件)。但是,访问未声明的变量是非法的。

在internetexplorer中,控制台对象实际上并没有定义,除非在加载窗口时打开了开发工具。

要解决您的问题,请将所有控制台打印内容包装在if语句中:

if (typeof window.console !== 'undefined') {
    ...
}

您还需要在打开开发人员工具后刷新每个页面,以便查看控制台打印<3 IE

这是关于未声明变量的一件有趣的事情。JS引擎试图将变量解析为window的属性。通常情况下,foo == window.foo

但是,如果该属性不存在,就会抛出一个错误。

alert(foo); // Syntax error: foo is not defined

(应该是"foo不是声明的"imho,但不管怎样。)当显式引用窗口的属性时,不会发生该错误:

alert(window.foo); // undefined

或声明该变量:

var foo;
alert(foo); // undefined

或将其用于初始化:

foo = 1; // window.foo = 1

奇怪的是,typeof操作符也阻止了这个错误:

alert(typeof foo); // "undefined"

综上所述:除非window的属性具有相同的名称,或者将其用作typeof的操作数,否则不能在表达式中使用未声明的变量。在您的示例中,window.console不存在,也没有var声明。这就是你出错的原因。

这个怎么样?还没试过

if (typeof console == "undefined" || typeof console.log == "undefined") var console = { log: function() {} };

编辑@yckart的答案

使用c.length作为定义c的函数的输入是行不通的。此外,当你应该向window.console.添加方法时,你只是用noop重新分配数组中的项目

(function(w){
  var c = 'assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,table,time,timeEnd,timeStamp,trace,warn'.split(','),
  noop = function () {};
  w.console = w.console || (function (len) {
    var ret = {};
    while (len--) { ret[c[len]] = noop; }
    return ret;
  }(c.length));
})(window);

您可以使用下面的内容为您提供额外程度的保险,即您已经涵盖了所有基础。首先使用typeof将避免任何undefined错误。使用===还将确保类型的名称实际上是字符串"undefined"。最后,您需要在函数签名中添加一个参数(我任意选择了logMsg)以确保一致性,因为您确实将要打印到控制台的任何内容传递给日志函数。这也使您的intellisense保持准确,并避免在您的JS感知IDE中出现任何警告/错误。

if(!window.console || typeof console === "undefined") {
  var console = { log: function (logMsg) { } };
}

受@Edgar Villegas Alvarado答案的启发,完成了方法并使其变得更简单:

(function(w){
  var c = 'assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,table,time,timeEnd,timeStamp,trace,warn'.split(','),
  noop = function () {};
  w.console = w.console || (function (len) {
    var ret = {};
    while (len--) { ret[c[len]] = noop; }
    return ret;
  }(c.length));
})(window);

编辑后放入IIFE并修复语法错误!

当开发工具关闭时,某些浏览器没有启用console。此外,在禁用控制台的WebViews或iFrame中也会遇到此问题。

这些情况下的错误为-Uncaught ReferenceError: console is not defined

受这里许多答案的启发,我为这个用例开发了一个库:https://github.com/sunnykgupta/jsLogger

功能:

  1. 它安全地覆盖console.log
  2. 如果控制台不可用,请小心(哦,是的,你也需要考虑这一点。)
  3. 存储所有日志(即使它们被抑制)以供以后检索
  4. 处理主要控制台功能,如logwarnerrorinfo