检查控制台是否存在

Roc*_*ngh 28 javascript asp.net jquery

我正在写一个插件.为此,我将记录一些事情,说警告,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() {};
Run Code Online (Sandbox Code Playgroud)

这项工作是正确还是有更好的选择?

ale*_*exn 34

你接近它了.但是你可以稍微缩短一下:

if(typeof console === "undefined") {
    console = {
        log: function() { },
        debug: function() { },
        ...
    };
}
Run Code Online (Sandbox Code Playgroud)

这允许您在console.log/console.debug etc不首先检查是否定义控制台对象的情况下使用.如果您要记录,我建议始终包含此片段,因为很容易忘记删除,如果没有控制台,它将破坏您的网站.


Lio*_*ior 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;
    }
}
Run Code Online (Sandbox Code Playgroud)