Javascript 在 IE 中测试 console.log 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7585351/
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-24 02:49:39  来源:igfitidea点击:

Testing for console.log statements in IE

javascriptinternet-explorerfirebug

提问by Michael BW

Possible Duplicate:
'console' is undefined error for internet explorer

可能重复:
“控制台”是 Internet Explorer 的未定义错误

If you have console.logstatements in your code, Internet Explorer will throw a JavaScript error (at least in IE7 which is what our intranet users have installed).

如果您console.log的代码中有语句,Internet Explorer 将抛出 JavaScript 错误(至少在我们的内网用户安装的 IE7 中)。

I am using Firefox for most of my development testing primarily because of the functionality provided by Firebug (where I use a lot of console statements) but I also need to test in IE.

我使用 Firefox 进行大部分开发测试,主要是因为 Firebug 提供的功能(我使用了很多控制台语句),但我也需要在 IE 中进行测试。

if I add the following to my JavaScript, the error does not get thrown.

如果我将以下内容添加到我的 JavaScript 中,则不会抛出错误。

var debugging = false;
if (typeof console == "undefined") 
    var console = { log: function() {} };  

The problem is that I would like to trigger an event if debugging mode is false. If I create a function to test whether debugging is false and do an action (at this point just an alert) but when I try do the following I receive an IE error saying Console is not defined.

问题是,如果调试模式为假,我想触发一个事件。如果我创建一个函数来测试调试是否为假并执行一个操作(此时只是一个警报)但是当我尝试执行以下操作时,我收到一个 IE 错误,提示Console is not defined

var debugging = false; // or true   
if (typeof console == "undefined") 
    var console = { log: function() {consoleMsg()} };   

function consoleMsg() {
    if(!debugging) {
    alert('Console.log event in Production Code');
}   

If someone could help me to fix my code, provide a better way to help me achieve my goal, or direct me to a resource to edumacate myself I would be very appreciative.

如果有人可以帮助我修复我的代码,提供一种更好的方法来帮助我实现我的目标,或者将我引导到一个资源来教育自己,我将非常感激。

回答by Joseph Silber

You don't have to jump through all these hoops. Simply check if the console exists before using it.

你不必跳过所有这些箍。只需在使用前检查控制台是否存在。

So, instead of:

所以,而不是:

console.log('foo');

Use:

用:

window.console && console.log('foo');

...and you won't get any errors.

...你不会得到任何错误。



Alternatively, you could just check for it at the top of your script, and if it's undefined, just fill it with an empty function:

或者,您可以在脚本的顶部检查它,如果它未定义,只需用一个空函数填充它:

// At the top of your script:
if ( ! window.console ) console = { log: function(){} };
// If you use other console methods, add them to the object literal above

// Then, anywhere in your script:
console.log('This message will be logged, but will not cause an error in IE7');


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 graphicdivine

'console' itself needs to be a function, as well as 'log'. So:

“控制台”本身需要是一个函数,以及“日志”。所以:

if(typeof(console) === 'undefined') {
    console = function(){};
    console.log = function(){consoleMsg()};
}   

回答by Bhesh Gurung

Did you try try-catch:

你有没有试过try-catch

var debugging = false; // or true 
try {  
    console.log();
} catch(ex) {
    /*var*/ console = { log: function() {consoleMsg()} };   
}

回答by Saxoier

(function(debug) {
    var console;

    function wrapConsoleMethod(fnName) {
        if(fnName in console)
            console[ fnName ] = function(fn) {
                return function() {
                    if(debug)
                        return fn.apply(console, arguments);
                    else
                        alert('Console event in Production Code');
                };
            }(console[ fnName ]);
        else
            ; // fn not in console
    };

    if(!('console' in window))
        window.console = {
            log : function() {}
            // ...
        };
    console = window.console;
    wrapConsoleMethod('log');
    // ...
})(true /* debug */);

console.log('test');