Brief solution sharing for browser compatible console objects

  • 2020-03-26 21:38:48
  • OfStack

When the browser cannot find the console object, we manually construct a console object with the same interface to place in the window. Empty methods and empty objects are used here. This way, even in very old browsers, the code containing console.xxxxx still works without errors.

The fix compatibility code attached below is placed before the first console.xxxx call, otherwise it is meaningless.

(function (){  

//Create an empty console object to avoid JS error reporting.

    window.console = {};  
var console = window.console;  

var funcs = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml',  
             'error', 'exception', 'group', 'groupCollapsed', 'groupEnd',  
             'info', 'log', 'markTimeline', 'profile', 'profileEnd',  
             'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn'];  
for(var i=0,l=funcs.length;i<l;i++) {  
    var func = funcs[i];  
        console[func] = function(){};  
    console.memory = {};  


Related articles: