2011-05-17 120 views
28

我正在编写一个插件。为此,我会记录一些事情,比如警告,necc等等。要记录它们,我将使用控制台,但如果某些浏览器不支持控制台,则可能会出现错误。要处理这个错误,我想使用这个代码:检查控制台是否存在

if (typeof console == 'undefined') console = {}; 
if (typeof console.log == 'undefined') console.log = function() {}; 
if (typeof console.debug == 'undefined') console.debug = function() {}; 
if (typeof console.info == 'undefined') console.info = function() {}; 
if (typeof console.warn == 'undefined') console.warn = function() {}; 
if (typeof console.error == 'undefined') console.error = function() {}; 

这个工作是否正确或有更好的选择?

回答

34

你正在接近它。然而,你可能会缩短一点:

if(typeof console === "undefined") { 
    console = { 
     log: function() { }, 
     debug: function() { }, 
     ... 
    }; 
} 

这允许您使用console.log/console.debug etc没有首先检查是否控制台对象被定义。如果您正在登录,我建议始终包含此代码段,因为它很容易忘记删除,并且如果没有控制台存在,它会破坏您的网站。

2
console && console.log("whatever"); 

这不行吗?

+0

我相信你可以做'console.log(“whatever”)||真的;'或类似的东西。我在几个月前看到它,并且不记得开发者是如何做到的,但我认为这是正确的。 – Endophage 2011-05-17 20:18:59

+0

@Endophage如果控制台不受支持,你会得到一个“无法调用方法”的未定义日志,一个正确的在线检查将是: 'console && console.log && console.log(“whatever”)' – Lior 2012-10-31 14:10:07

9

这种方法可以更容易地添加/修改/删除在未来的方法和更优雅和更少的冗余比大多数提供:

if (!"console" in window || typeof console == "undefined") { 
    var methods = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"]; 
    var emptyFn = function() {}; 
    window.console = {}; 
    for (var i = 0; i < methods.length; ++i) { 
     window.console[methods[i]] = emptyFn; 
    } 
} 
0

如何缩短@alexn的回答有点

window.console = window.console || { debug: function(){}, log: function() { } };