javascript 检查控制台是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6036377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check whether console is present
提问by Rocky Singh
I am writing a plugin. For that I will log a few things, say warnings, necc things, etc. To log them I will use console, but there can be an error if some browser doesn't support console. To handle this error, I am thinking of using this code:
我正在写一个插件。为此,我将记录一些内容,例如警告、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() {};
Will this work right or is there a better option?
这会正常工作还是有更好的选择?
回答by alexn
You're approaching it right. You could however shorten it a bit:
你正在接近它。但是,您可以将其缩短一点:
if(typeof console === "undefined") {
console = {
log: function() { },
debug: function() { },
...
};
}
This allows you to use console.log/console.debug etc
without first checking if a console object is defined. I recommend to always include this snippet if you are logging since it is easy to forget to remove and it will break your site if no console is present.
这允许您在console.log/console.debug etc
不首先检查控制台对象是否已定义的情况下使用。如果您正在登录,我建议始终包含此代码段,因为它很容易忘记删除,如果没有控制台,它会破坏您的站点。
回答by Lior
This approach makes it easier to add/change/remove methods in the future and is more elegant and less redundant than most offered:
这种方法使将来添加/更改/删除方法更容易,并且比大多数提供的方法更优雅且冗余更少:
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;
}
}
回答by Arindam
console && console.log("whatever");
Does this not work ?
这不起作用吗?
回答by Aravindan R
How about using a library for logging?
如何使用库进行日志记录?
UPDATE:You could use the below script to avoid console
errors in browsers that lack a console.
更新:您可以使用以下脚本来避免console
在缺少控制台的浏览器中出现错误。
https://github.com/h5bp/html5-boilerplate/blob/master/src/js/plugins.js
https://github.com/h5bp/html5-boilerplate/blob/master/src/js/plugins.js
回答by Rene Vorndran
How about shortening @alexn 's answer a bit
如何缩短@alexn 的回答
window.console = window.console || { debug: function(){}, log: function() { } };