Internet Explorer: “console is not defined” Error

前端 未结 9 1615
天涯浪人
天涯浪人 2020-12-05 18:33

I was using console.log() in some JavaScript I wrote and an error of: console is not defined was thrown in Internet Explorer (worked fine in other

9条回答
  •  半阙折子戏
    2020-12-05 18:53

    Other answers gave you the root cause. However, there's a better solution than using if before any call to console.*

    Add this (once) before including any of your scripts that use console:

    //Ensures there will be no 'console is undefined' errors
    window.console = window.console || (function(){
        var c = {}; c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile = c.clear = c.exception = c.trace = c.assert = function(s){};
        return c;
    })();
    

    This will create a 'pseudo' console only if it doesn't exist, so that 'console is undefined' errors will go away and you won't have to ask if console exists everytime. With this, you just call console.log or any console method anywhere, without problems.

    Hope this helps. Cheers

提交回复
热议问题