'console' is undefined error for Internet

2018-12-31 05:59发布

I'm using Firebug and have some statements like:

console.log("...");

in my page. In IE8 (probably earlier versions too) I get script errors saying 'console' is undefined. I tried putting this at the top of my page:

<script type="text/javascript">
    if (!console) console = {log: function() {}};
</script>

still I get the errors. Any way to get rid of the errors?

21条回答
ら面具成の殇う
2楼-- · 2018-12-31 06:39

In IE9, if console is not opened, this code:

alert(typeof console);

will show "object", but this code

alert(typeof console.log);

will throw TypeError exception, but not return undefined value;

So, guaranteed version of code will look similar to this:

try {
    if (window.console && window.console.log) {
        my_console_log = window.console.log;
    }
} catch (e) {
    my_console_log = function() {};
}
查看更多
一个人的天荒地老
3楼-- · 2018-12-31 06:42

Try

if (!window.console) console = ...

An undefined variable cannot be referred directly. However, all global variables are attributes of the same name of the global context (window in case of browsers), and accessing an undefined attribute is fine.

Or use if (typeof console === 'undefined') console = ... if you want to avoid the magic variable window, see @Tim Down's answer.

查看更多
时光乱了年华
4楼-- · 2018-12-31 06:43
console = console || { 
    debug: function(){}, 
    log: function(){}
    ...
}
查看更多
登录 后发表回答