'console' is undefined error for Internet Explorer

前端 未结 21 1720
-上瘾入骨i
-上瘾入骨i 2020-11-22 04:49

I\'m using Firebug and have some statements like:

console.log(\"...\");

in my page. In IE8 (probably earlier versions too) I get script err

21条回答
  •  萌比男神i
    2020-11-22 05:15

    After having oh so many problems with this thing (it's hard to debug the error since if you open the developer console the error no longer happens!) I decided to make an overkill code to never have to bother with this ever again:

    if (typeof window.console === "undefined")
        window.console = {};
    
    if (typeof window.console.debug === "undefined")
        window.console.debug= function() {};
    
    if (typeof window.console.log === "undefined")
        window.console.log= function() {};
    
    if (typeof window.console.error === "undefined")
        window.console.error= function() {alert("error");};
    
    if (typeof window.console.time === "undefined")
        window.console.time= function() {};
    
    if (typeof window.console.trace === "undefined")
        window.console.trace= function() {};
    
    if (typeof window.console.info === "undefined")
        window.console.info= function() {};
    
    if (typeof window.console.timeEnd === "undefined")
        window.console.timeEnd= function() {};
    
    if (typeof window.console.group === "undefined")
        window.console.group= function() {};
    
    if (typeof window.console.groupEnd === "undefined")
        window.console.groupEnd= function() {};
    
    if (typeof window.console.groupCollapsed === "undefined")
        window.console.groupCollapsed= function() {};
    
    if (typeof window.console.dir === "undefined")
        window.console.dir= function() {};
    
    if (typeof window.console.warn === "undefined")
        window.console.warn= function() {};
    

    Personaly I only ever use console.log and console.error, but this code handles all the other functions as shown in the Mozzila Developer Network: https://developer.mozilla.org/en-US/docs/Web/API/console. Just put that code on the top of your page and you are done forever with this.

提交回复
热议问题