Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

javascript - Internet Explorer: "console is not defined" Error

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 browsers).

I have replaced it with:

if (console) console.log("...");

If console is undefined, I would expect the condition to evaluate as false. Ergo, the statement console.log wouldn't be executed and shouldn't throw an error.

Instead, an error of: console is not defined at character 4 is thrown.

Is this a IE bug? Or is that "if" condition really illegal? It seems absurd because if if (console) is illegal, then if (console==undefined) should be illegal too.

How are you supposed to check for undefined variables?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...