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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3326650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:09:55  来源:igfitidea点击:

'console' is undefined error for Internet Explorer

javascriptinternet-explorerinternet-explorer-8ie-developer-tools

提问by user246114

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(也可能是早期版本)中,我收到脚本错误,提示“控制台”未定义。我试着把它放在我的页面顶部:

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

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

我仍然收到错误。有什么办法可以摆脱错误?

回答by kennytm

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 (windowin case of browsers), and accessing an undefined attribute is fine.

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

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

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

回答by Peter Tseng

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 consoleand undefined console.debug(and other missing methods).

函数闭包包装器将变量范围限定为不定义任何变量。这可以防止未定义console和未定义console.debug(以及其他丢失的方法)。

EDIT:I noticed that HTML5 Boilerplateuses 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/plugins.js 文件中使用类似的代码,如果您正在寻找(可能)保持最新的解决方案。

回答by Tim Down

Another alternative is the typeofoperator:

另一种选择是typeof运算符:

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

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

另一种选择是使用日志库,例如我自己的log4javascript

回答by Vinícius Moraes

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

回答by iblamefish

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:

或者,如果编辑每个 console.log 行不可能或不可行,我会创建一个假控制台:

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

回答by iblamefish

You can use console.log()if you have Developer Toolsin IE8 opened and also you can use the Consoletextbox on script tab.

您可以使用console.log(),如果你有Developer Tools在IE8打开,也可以使用Console脚本选项卡上的文本框中。

回答by TWiStErRob

Based on two previous answers by

基于之前的两个答案

and the documentations for

和文件

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,它会通过 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,您可以用警报替换日志记录(愚蠢但有效),然后包含以下怪物(我称其为 console.js):[随意删除您认为合适的评论,我将它们留作参考,最小化器可以解决它们]:

<!--[if lte IE 7]>
<SCRIPT LANGUAGE="javascript">
    (window.console = window.console || {}).log = function() { return window.alert.apply(window, arguments); };
</SCRIPT>
<![endif]-->
<script type="text/javascript" src="console.js"></script>

and console.js:

和控制台.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];
            }
        }
    })();

回答by insign

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

回答by Ruben Decrop

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

我只在我的代码中使用 console.log。所以我包括一个非常短的 2 班轮

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

回答by bonbonez

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