Home  >  Article  >  Web Front-end  >  浏览器兼容console对象的简要解决方案分享_javascript技巧

浏览器兼容console对象的简要解决方案分享_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:19:001108browse

浏览器报找不到console对象,那我们就手动构造一个接口完全一致的console对象 置于window中。这里采用了空方法和空对象。如此一来即使在很old的浏览器中,含有console.xxxxx的代码依然不会报错,完美运行。

下面附上修复兼容代码,要置于置于第一句console.xxxx调用之前,否则没有意义。

复制代码 代码如下:

(function (){ 

//创建空console对象,避免JS报错 

if(!window.console) 
    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    var func = funcs[i]; 
    if(!console[func]) 
        console[func] = function(){}; 

if(!console.memory) 
    console.memory = {}; 

})();
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn