时间:2010-07-24 19:55:42

标签: javascript internet-explorer internet-explorer-8 ie-developer-tools

21 个答案:

答案 0 :(得分:375)

答案 1 :(得分:316)

将以下内容粘贴到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;
  }
})();

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

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

答案 2 :(得分:73)

答案 3 :(得分:46)

要获得更强大的解决方案,请使用这段代码(取自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;
        }
    }
}());

答案 4 :(得分:13)

答案 5 :(得分:10)

如果您在IE8中打开console.log(),则可以使用Developer Tools,也可以在脚本标签上使用Console文本框。

答案 6 :(得分:7)

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

答案 7 :(得分:6)

在IE9中,如果未打开控制台,则此代码为:

alert(typeof console);

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

alert(typeof console.log);

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

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

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

答案 8 :(得分:6)

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

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

答案 9 :(得分:6)

基于之前的两个答案

的文件

这是针对该问题的尽力而为的实现,这意味着如果存在实际存在的console.log,它将通过console.log填补不存在的方法的空白。

例如对于IE6 / 7,您可以使用alert替换日志记录(愚蠢但有效),然后包含下面的怪物(我称之为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>

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

答案 10 :(得分:2)

注意到OP正在使用带有IE的Firebug,所以假设它是Firebug Lite。这是一个时髦的情况,因为在打开调试器窗口时在IE中定义了控制台,但是当Firebug已经运行时会发生什么?不确定,但也许是&#34; firebugx.js&#34;方法可能是在这种情况下测试的好方法:

源:

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 < names.length; ++i)
            window.console[names[i]] = function() {}
    }

(更新链接12/2014)

答案 11 :(得分:1)

要在IE中进行调试,请查看此log4javascript

答案 12 :(得分:1)

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

答案 13 :(得分:1)

对于仅限于console.log(无调试,跟踪,...)的IE8或控制台支持,您可以执行以下操作:

  • 如果控制台或console.log未定义:为其创建虚拟函数 控制台功能(跟踪,调试,日志,......)

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

  • 否则,如果定义了console.log(IE8)并且未定义console.debug(任何其他):将所有日志记录功能重定向到console.log,这样可以保留这些日志!

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

不确定各种IE版本中的断言支持,但欢迎任何建议。也在这里发布了这个答案:How can I use console logging in Internet Explorer?

答案 14 :(得分:1)

我正在使用fauxconsole;我对css进行了一些修改,使其看起来更好但效果非常好。

答案 15 :(得分:0)

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

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

答案 16 :(得分:0)

有时控制台可以在IE8 / 9中运行,但在其他时候会失败。这种不稳定的行为取决于您是否打开了开发人员工具,并在stackoverflow问题Does IE9 support console.log, and is it a real function?

中进行了描述

答案 17 :(得分:0)

在IE9的子窗口中运行console.log遇到类似的问题,由window.open函数创建。

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

我通过将log登录到下一个函数(下面是模块的片段)来处理这个问题

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

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

        while (!!context && searchDepth < searchDepthMax)
        {
            if (typeof context.console !== 'undefined') return context.console;

            context = context.opener;
            searchDepth++;
        }

        return null;
    },
    log: function(message){
        var _console = this.getConsole();
        if (!!_console) _console.log(message);
    }

答案 18 :(得分:0)

TypeScript中控制台的存根:

class test (type)
    def __str__(self)
    return str.__class__

class vtest (object)
    self.repr(str)

答案 19 :(得分:-2)

在遇到这么多问题之后(很难调试错误,因为如果你打开开发人员控制台,错误就不再发生了!)我决定制作一个过度杀伤代码,永远不必再烦恼了:

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我只使用console.log和console.error,但是这段代码处理Mozzila开发者网络中显示的所有其他功能:https://developer.mozilla.org/en-US/docs/Web/API/console。 只需将代码放在页面顶部,就可以永久完成。

答案 20 :(得分:-10)

您可以直接在Firefox中使用console.log(...),但不能在IE中使用。在IE中,您必须使用window.console。