Testing for console.log statements in IE [duplicate]

眉间皱痕 提交于 2019-11-27 06:10:26
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):

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

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

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

Did you try try-catch:

var debugging = false; // or true 
try {  
    console.log();
} catch(ex) {
    /*var*/ console = { log: function() {consoleMsg()} };   
}
(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');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!