热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

“控制台”是InternetExplorer的未定义错误。-'console'isundefinederrorforInternetExplorer

ImusingFirebugandhavesomestatementslike:我使用Firebug,有一些语句:console.log();inmypage

I'm using Firebug and have some statements like:

我使用Firebug,有一些语句:

console.log("...");

in my page. In IE8 (probably earlier versions too) I get script errors saying 'console' is undefined. I tried putting this at the top of my page:

在我的页面。在IE8(可能更早的版本)中,我得到了脚本错误,说“控制台”是没有定义的。我试着把它放在我的页面顶端:


still I get the errors. Any way to get rid of the errors?

我还是会犯错误。有什么方法可以去掉这些错误吗?

21 个解决方案

#1


370  

Try

试一试

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

An undefined variable cannot be referred directly. However, all global variables are attributes of the same name of the global context (window in case of browsers), and accessing an undefined attribute is fine.

未定义的变量不能直接引用。但是,所有全局变量都是全局上下文的相同名称的属性(在浏览器中是窗口),并且访问未定义的属性是好的。

Or use if (typeof cOnsole=== 'undefined') cOnsole= ... if you want to avoid the magic variable window, see @Tim Down's answer.

或者使用if(控制台== 'undefined')控制台=……如果您想要避免神奇的变量窗口,请参见@Tim Down的答案。

#2


312  

Paste the following at the top of your Javascript (before using the console):

在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;
  }
})();

The function closure wrapper is to scope the variables as to not define any variables. This guards against both undefined console and undefined console.debug (and other missing methods).

函数闭包包装器是对变量进行范围界定,而不是定义任何变量。此守护程序针对未定义的控制台和未定义的console.debug(和其他丢失的方法)。

EDIT: I noticed that HTML5 Boilerplate uses similar code in its js/plugins.js file, if you're looking for a solution that will (probably) be kept up-to-date.

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

#3


72  

Another alternative is the typeof operator:

另一种选择是:

if (typeof cOnsole== "undefined") {
    this.cOnsole= {log: function() {}};
}

Yet another alternative is to use a logging library, such as my own log4Javascript.

另一种选择是使用日志库,比如我自己的log4Javascript。

#4


46  

For a more robust solution, use this piece of code (taken from twitter's source code):

对于一个更健壮的解决方案,使用这段代码(取自twitter的源代码):

// Avoid `console` errors in browsers that lack a console.
(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var cOnsole= (window.cOnsole= window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());

#5


13  

In my scripts, I either use the shorthand:

在我的脚本中,我要么使用速记:

window.console && console.log(...) // only log if the function exists

or, if it's not possible or feasible to edit every console.log line, I create a fake console:

或者,如果不可能编辑每个控制台。日志行,我创建了一个假控制台:

// check to see if console exists. If not, create an empty object for it,
// then create and empty logging function which does nothing. 
//
// REMEMBER: put this before any other console.log calls
!window.console && (window.cOnsole= {} && window.console.log = function () {});

#6


10  

You can use console.log() if you have Developer Tools in IE8 opened and also you can use the Console textbox on script tab.

如果您在IE8中有开发工具,也可以在script选项卡上使用控制台文本框,那么您可以使用console.log()。

#7


7  

if (typeof cOnsole== "undefined") {
  this.cOnsole= {
    log: function() {},
    info: function() {},
    error: function() {},
    warn: function() {}
  };
}

#8


6  

In IE9, if console is not opened, this code:

在IE9中,如果没有打开控制台,则该代码:

alert(typeof console);

will show "object", but this code

将显示“对象”,但此代码?

alert(typeof console.log);

will throw TypeError exception, but not return undefined value;

将抛出TypeError异常,但不返回未定义值;

So, guaranteed version of code will look similar to this:

因此,有保证的代码版本看起来类似于:

try {
    if (window.console && window.console.log) {
        my_console_log = window.console.log;
    }
} catch (e) {
    my_console_log = function() {};
}

#9


6  

I am only using console.log in my code. So I include a very short 2 liner

我只是使用控制台。登录我的代码。所以我包括了一个非常短的2号班轮。

var cOnsole= console || {};
console.log = console.log || function(){};

#10


6  

Based on two previous answers by

根据之前的两个答案。

  • Vinícius Moraes
  • 维尼·莫拉
  • Peter Tseng
  • 彼得曾

and the documentations for

和文件

  • Internet Explorer (IE 10)
  • Internet Explorer(IE 10)
  • Safari (2012. 07. 23.)
  • Safari(2012。07年。23)。
  • Firefox (2013. 05. 20.)
  • Firefox(2013。05。20)。
  • Chrome (2013. 01. 25.) and Chrome (2012. 10. 04.)
  • Chrome(2013。01。25)和铬(2012。10。04)。
  • and some of my knowledge
  • 还有我的一些知识。

Here's a best effort implementation for the issue, meaning if there's a console.log which actually exists, it fills in the gaps for non-existing methods via console.log.

这里是这个问题的最佳实现,这意味着如果有控制台的话。日志实际上是存在的,它通过console.log来填补非现有方法的空白。

For example for IE6/7 you can replace logging with alert (stupid but works) and then include the below monster (I called it console.js): [Feel free to remove comments as you see fit, I left them in for reference, a minimizer can tackle them]:

例如,对于IE6/7,你可以用alert(愚蠢的但有效的)来代替日志记录,然后包括下面的怪物(我叫它console.js):(在你认为合适的时候可以随意删除注释,我把它们留给了参考,一个最小化器可以处理它们):



and console.js:

和console.js:

    /**
     * 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
     */
    (function() {
        var cOnsole= (window.cOnsole= window.console || {});
        var noop = function () {};
        var log = console.log || noop;
        var start = function(name) { return function(param) { log("Start " + name + ": " + param); } };
        var end = function(name) { return function(param) { log("End " + name + ": " + param); } };

        var methods = {
            // Internet Explorer (IE 10): http://msdn.microsoft.com/en-us/library/ie/hh772169(v=vs.85).aspx#methods
            // assert(test, message, optionalParams), clear(), count(countTitle), debug(message, optionalParams), dir(value, optionalParams), dirxml(value), error(message, optionalParams), group(groupTitle), groupCollapsed(groupTitle), groupEnd([groupTitle]), info(message, optionalParams), log(message, optionalParams), msIsIndependentlyComposed(oElementNode), profile(reportName), profileEnd(), time(timerName), timeEnd(timerName), trace(), warn(message, optionalParams)
            // "assert", "clear", "count", "debug", "dir", "dirxml", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "msIsIndependentlyComposed", "profile", "profileEnd", "time", "timeEnd", "trace", "warn"

            // Safari (2012. 07. 23.): https://developer.apple.com/library/safari/#documentation/AppleApplications/Conceptual/Safari_Developer_Guide/DebuggingYourWebsite/DebuggingYourWebsite.html#//apple_ref/doc/uid/TP40007874-CH8-SW20
            // assert(expression, message-object), count([title]), debug([message-object]), dir(object), dirxml(node), error(message-object), group(message-object), groupEnd(), info(message-object), log(message-object), profile([title]), profileEnd([title]), time(name), markTimeline("string"), trace(), warn(message-object)
            // "assert", "count", "debug", "dir", "dirxml", "error", "group", "groupEnd", "info", "log", "profile", "profileEnd", "time", "markTimeline", "trace", "warn"

            // Firefox (2013. 05. 20.): https://developer.mozilla.org/en-US/docs/Web/API/console
            // debug(obj1 [, obj2, ..., objN]), debug(msg [, subst1, ..., substN]), dir(object), error(obj1 [, obj2, ..., objN]), error(msg [, subst1, ..., substN]), group(), groupCollapsed(), groupEnd(), info(obj1 [, obj2, ..., objN]), info(msg [, subst1, ..., substN]), log(obj1 [, obj2, ..., objN]), log(msg [, subst1, ..., substN]), time(timerName), timeEnd(timerName), trace(), warn(obj1 [, obj2, ..., objN]), warn(msg [, subst1, ..., substN])
            // "debug", "dir", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "time", "timeEnd", "trace", "warn"

            // Chrome (2013. 01. 25.): https://developers.google.com/chrome-developer-tools/docs/console-api
            // assert(expression, object), clear(), count(label), debug(object [, object, ...]), dir(object), dirxml(object), error(object [, object, ...]), group(object[, object, ...]), groupCollapsed(object[, object, ...]), groupEnd(), info(object [, object, ...]), log(object [, object, ...]), profile([label]), profileEnd(), time(label), timeEnd(label), timeStamp([label]), trace(), warn(object [, object, ...])
            // "assert", "clear", "count", "debug", "dir", "dirxml", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "profile", "profileEnd", "time", "timeEnd", "timeStamp", "trace", "warn"
            // Chrome (2012. 10. 04.): https://developers.google.com/web-toolkit/speedtracer/logging-api
            // markTimeline(String)
            // "markTimeline"

            assert: noop, clear: noop, trace: noop, count: noop, timeStamp: noop, msIsIndependentlyComposed: noop,
            debug: log, info: log, log: log, warn: log, error: log,
            dir: log, dirxml: log, markTimeline: log,
            group: start('group'), groupCollapsed: start('groupCollapsed'), groupEnd: end('group'),
            profile: start('profile'), profileEnd: end('profile'),
            time: start('time'), timeEnd: end('time')
        };

        for (var method in methods) {
            if ( methods.hasOwnProperty(method) && !(method in console) ) { // define undefined methods as best-effort methods
                console[method] = methods[method];
            }
        }
    })();

#11


2  

Noticed that OP is using Firebug with IE, so assume it's Firebug Lite. This is a funky situation as console gets defined in IE when the debugger window is opened, but what happens when Firebug is already running? Not sure, but perhaps the "firebugx.js" method might be a good way to test in this situation:

注意到OP正在使用IE的Firebug,所以假设它是Firebug Lite。当调试器窗口打开时,在IE中定义控制台,但是当Firebug已经运行时,会发生什么情况呢?不确定,但可能是“firebugx”。在这种情况下,js“方法可能是一个很好的测试方法:

source:

来源:

https://code.google.com/p/fbug/source/browse/branches/firebug1.2/lite/firebugx.js?r=187

https://code.google.com/p/fbug/source/browse/branches/firebug1.2/lite/firebugx.js?r=187

    if (!window.console || !console.firebug) {
        var names = [
            "log", "debug", "info", "warn", "error", "assert",
            "dir","dirxml","group","groupEnd","time","timeEnd",
            "count","trace","profile","profileEnd"
        ];
        window.cOnsole= {};
        for (var i = 0; i 

(updated links 12/2014)

(更新链接12/2014)

#12


1  

I'm using fauxconsole; I modified the css a bit so that it looks nicer but works very well.

我用fauxconsole;我稍微修改了一下css,使它看起来更好,但是效果很好。

#13


1  

For debugging in IE, check out this log4Javascript

要调试IE,请查看此log4Javascript。

#14


1  

For IE8 or console support limited to console.log (no debug, trace, ...) you can do the following:

用于IE8或控制台支持仅限于控制台。日志(没有调试,跟踪,…)您可以执行以下操作:

  • If console OR console.log undefined: Create dummy functions for console functions (trace, debug, log, ...)

    如果控制台或控制台。日志未定义:为控制台功能创建虚拟函数(跟踪、调试、日志、…)

    window.cOnsole= { debug : function() {}, ...};

    窗口。控制台= {debug: function() {};

  • Else if console.log is defined (IE8) AND console.debug (any other) is not defined: redirect all logging functions to console.log, this allows to keep those logs !

    如果控制台。日志被定义(IE8)和console.debug(任何其他的)都没有定义:将所有日志功能重定向到控制台。日志,这允许保留那些日志!

    window.cOnsole= { debug : window.console.log, ...};

    窗口。控制台= {debug: window.console。日志,…};

Not sure about the assert support in various IE versions, but any suggestions are welcome. Also posted this answer here: How can I use console logging in Internet Explorer?

不确定是否支持各种IE版本,但是欢迎任何建议。在这里也发布了这个答案:如何在Internet Explorer中使用控制台日志记录?

#15


1  

cOnsole= console || { 
    debug: function(){}, 
    log: function(){}
    ...
}

#16


0  

You can use the below to give an extra degree of insurance that you've got all bases covered. Using typeof first will avoid any undefined errors. Using === will also ensure that the name of the type is actually the string "undefined". Finally, you'll want to add a parameter to the function signature (I chose logMsg arbitrarily) to ensure consistency, since you do pass whatever you want printed to the console to the log function. This also keep you intellisense accurate and avoids any warnings/errors in your JS aware IDE.

你可以用下面的方法给你额外的保险,你已经得到了所有的基础。首先使用typeof将避免任何未定义的错误。使用===还将确保类型的名称实际上是“未定义的字符串”。最后,您需要向函数签名添加一个参数(我随意选择了logMsg),以确保一致性,因为您可以将任何您想要打印到控制台的内容传递给日志函数。这也会使你的智能感知更加准确,避免你的JS中出现任何警告/错误。

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

#17


0  

Sometimes console will work in IE8/9 but fail at other times. This erratic behaviour depends on whether you have developer tools open and is described in stackoverflow question Does IE9 support console.log, and is it a real function?

有时控制台会在IE8/9中工作,但在其他时候会失败。这种不稳定的行为取决于您是否打开了开发工具,并且在stackoverflow问题中描述了IE9支持控制台。log,它是一个实函数吗?

#18


0  

Encountered similar problem running console.log in child windows in IE9, created by window.open function.

遇到类似的问题运行控制台。在IE9中通过窗口创建的子窗口。打开功能。

It seems that in this case console is defined only in parent window and is undefined in child windows until you refresh them. Same applies to children of child windows.

似乎在这种情况下,控制台仅在父窗口中定义,在子窗口中未定义,直到您刷新它们。同样适用于儿童窗口的儿童。

I deal with this issue by wrapping log in next function (below is fragment of module)

我将在接下来的函数中封装日志来处理这个问题(下面是模块的片段)

getConsole: function()
    {
        if (typeof console !== 'undefined') return console;

        var searchDepthMax = 5,
            searchDepth = 0,
            cOntext= window.opener;

        while (!!context && searchDepth 

#19


0  

Stub of console in TypeScript:

打字稿中控制台的存根:

if (!window.console) {
cOnsole= {
    assert: () => { },
    clear: () => { },
    count: () => { },
    debug: () => { },
    dir: () => { },
    dirxml: () => { },
    error: () => { },
    group: () => { },
    groupCollapsed: () => { },
    groupEnd: () => { },
    info: () => { },
    log: () => { },
    msIsIndependentlyComposed: (e: Element) => false,
    profile: () => { },
    profileEnd: () => { },
    select: () => { },
    time: () => { },
    timeEnd: () => { },
    trace: () => { },
    warn: () => { },
    }
};

#20


-2  

After having oh so many problems with this thing (it's hard to debug the error since if you open the developer console the error no longer happens!) I decided to make an overkill code to never have to bother with this ever again:

在处理了这么多问题之后(很难调试错误,因为如果打开开发控制台,错误就不再发生了!)我决定做一个超杀代码,从此以后再也不用费心了:

if (typeof window.cOnsole=== "undefined")
    window.cOnsole= {};

if (typeof window.console.debug === "undefined")
    window.console.debug= function() {};

if (typeof window.console.log === "undefined")
    window.console.log= function() {};

if (typeof window.console.error === "undefined")
    window.console.error= function() {alert("error");};

if (typeof window.console.time === "undefined")
    window.console.time= function() {};

if (typeof window.console.trace === "undefined")
    window.console.trace= function() {};

if (typeof window.console.info === "undefined")
    window.console.info= function() {};

if (typeof window.console.timeEnd === "undefined")
    window.console.timeEnd= function() {};

if (typeof window.console.group === "undefined")
    window.console.group= function() {};

if (typeof window.console.groupEnd === "undefined")
    window.console.groupEnd= function() {};

if (typeof window.console.groupCollapsed === "undefined")
    window.console.groupCollapsed= function() {};

if (typeof window.console.dir === "undefined")
    window.console.dir= function() {};

if (typeof window.console.warn === "undefined")
    window.console.warn= function() {};

Personaly I only ever use console.log and console.error, but this code handles all the other functions as shown in the Mozzila Developer Network: https://developer.mozilla.org/en-US/docs/Web/API/console. Just put that code on the top of your page and you are done forever with this.

我只使用控制台。日志和控制台。错误,但是这段代码处理了Mozzila Developer网络中显示的所有其他功能:https://developer.mozilla.org/en-US/docs/Web/API/console。只要把这些代码放在你的页面的顶部,你就会永远这样做。

#21


-9  

You can use console.log(...) directly in Firefox but not in IEs. In IEs you have to use window.console.

可以直接在Firefox中使用console.log(…),但不可以在IEs中使用。在IEs中,你必须使用window.console。


推荐阅读
author-avatar
zdl
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有