我使用Firebug,并有一些语句像:
console.log("...");
在我的页面上。在IE8(可能是更早的版本),我得到脚本错误说“控制台”是未定义的。我试着把这个放在我页面的顶部:
<script type="text/javascript">
if (!console) console = {log: function() {}};
</script>
我还是会得到错误。有办法消除错误吗?
我使用Firebug,并有一些语句像:
console.log("...");
在我的页面上。在IE8(可能是更早的版本),我得到脚本错误说“控制台”是未定义的。我试着把这个放在我页面的顶部:
<script type="text/javascript">
if (!console) console = {log: function() {}};
</script>
我还是会得到错误。有办法消除错误吗?
当前回答
在我的脚本中,我要么使用速记:
window.console && console.log(...) // only log if the function exists
或者,如果不可能编辑每一个console.log行,我创建一个假控制台:
// check to see if console exists. If not, create an empty object for it,
// then create and empty logging function which does nothing.
//
// REMEMBER: put this before any other console.log calls
!window.console && (window.console = {} && window.console.log = function () {});
其他回答
注意到OP在IE中使用Firebug,所以假设它是Firebug Lite。当调试器窗口打开时,在IE中定义控制台,这是一种奇怪的情况,但是当Firebug已经在运行时会发生什么呢?不确定,但在这种情况下,"firebugx.js"方法可能是一个很好的测试方法:
来源:
https://code.google.com/p/fbug/source/browse/branches/firebug1.2/lite/firebugx.js?r=187
if (!window.console || !console.firebug) {
var names = [
"log", "debug", "info", "warn", "error", "assert",
"dir","dirxml","group","groupEnd","time","timeEnd",
"count","trace","profile","profileEnd"
];
window.console = {};
for (var i = 0; i < names.length; ++i)
window.console[names[i]] = function() {}
}
(更新链接12/2014)
console = console || {
debug: function(){},
log: function(){}
...
}
在有这么多问题之后(很难调试错误,因为如果你打开开发人员控制台,错误就不再发生了!)我决定做一个多余的代码,这样就再也不用为这个问题烦恼了:
if (typeof window.console === "undefined")
window.console = {};
if (typeof window.console.debug === "undefined")
window.console.debug= function() {};
if (typeof window.console.log === "undefined")
window.console.log= function() {};
if (typeof window.console.error === "undefined")
window.console.error= function() {alert("error");};
if (typeof window.console.time === "undefined")
window.console.time= function() {};
if (typeof window.console.trace === "undefined")
window.console.trace= function() {};
if (typeof window.console.info === "undefined")
window.console.info= function() {};
if (typeof window.console.timeEnd === "undefined")
window.console.timeEnd= function() {};
if (typeof window.console.group === "undefined")
window.console.group= function() {};
if (typeof window.console.groupEnd === "undefined")
window.console.groupEnd= function() {};
if (typeof window.console.groupCollapsed === "undefined")
window.console.groupCollapsed= function() {};
if (typeof window.console.dir === "undefined")
window.console.dir= function() {};
if (typeof window.console.warn === "undefined")
window.console.warn= function() {};
我个人只使用console.log和console。错误,但这段代码处理所有其他函数显示在Mozzila开发者网络:https://developer.mozilla.org/en-US/docs/Web/API/console。 只要把代码放在页面的顶部,你就永远不用这样做了。
根据之前的两个答案
维尼修斯·莫赖斯 曾国藩
和文件
Internet Explorer (ie10) Safari(2012。07. 23)。 Firefox(2013。05. 20)。 Chrome(2013。01. 25.)和Chrome(2012。10. 04)。 还有我的一些知识
下面是针对该问题的最佳实现,这意味着如果有一个真正存在的console.log,它将通过console.log填补不存在方法的空白。
例如,对于IE6/7,你可以用alert代替日志记录(愚蠢但有效),然后包括下面的怪物(我称之为console.js): [请随意删除你认为合适的评论,我把它们留作参考,最小化可以解决它们]:
<!--[if lte IE 7]>
<SCRIPT LANGUAGE="javascript">
(window.console = window.console || {}).log = function() { return window.alert.apply(window, arguments); };
</SCRIPT>
<![endif]-->
<script type="text/javascript" src="console.js"></script>
和console.js:
/**
* Protect window.console method calls, e.g. console is not defined on IE
* unless dev tools are open, and IE doesn't define console.debug
*/
(function() {
var console = (window.console = window.console || {});
var noop = function () {};
var log = console.log || noop;
var start = function(name) { return function(param) { log("Start " + name + ": " + param); } };
var end = function(name) { return function(param) { log("End " + name + ": " + param); } };
var methods = {
// Internet Explorer (IE 10): http://msdn.microsoft.com/en-us/library/ie/hh772169(v=vs.85).aspx#methods
// assert(test, message, optionalParams), clear(), count(countTitle), debug(message, optionalParams), dir(value, optionalParams), dirxml(value), error(message, optionalParams), group(groupTitle), groupCollapsed(groupTitle), groupEnd([groupTitle]), info(message, optionalParams), log(message, optionalParams), msIsIndependentlyComposed(oElementNode), profile(reportName), profileEnd(), time(timerName), timeEnd(timerName), trace(), warn(message, optionalParams)
// "assert", "clear", "count", "debug", "dir", "dirxml", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "msIsIndependentlyComposed", "profile", "profileEnd", "time", "timeEnd", "trace", "warn"
// Safari (2012. 07. 23.): https://developer.apple.com/library/safari/#documentation/AppleApplications/Conceptual/Safari_Developer_Guide/DebuggingYourWebsite/DebuggingYourWebsite.html#//apple_ref/doc/uid/TP40007874-CH8-SW20
// assert(expression, message-object), count([title]), debug([message-object]), dir(object), dirxml(node), error(message-object), group(message-object), groupEnd(), info(message-object), log(message-object), profile([title]), profileEnd([title]), time(name), markTimeline("string"), trace(), warn(message-object)
// "assert", "count", "debug", "dir", "dirxml", "error", "group", "groupEnd", "info", "log", "profile", "profileEnd", "time", "markTimeline", "trace", "warn"
// Firefox (2013. 05. 20.): https://developer.mozilla.org/en-US/docs/Web/API/console
// debug(obj1 [, obj2, ..., objN]), debug(msg [, subst1, ..., substN]), dir(object), error(obj1 [, obj2, ..., objN]), error(msg [, subst1, ..., substN]), group(), groupCollapsed(), groupEnd(), info(obj1 [, obj2, ..., objN]), info(msg [, subst1, ..., substN]), log(obj1 [, obj2, ..., objN]), log(msg [, subst1, ..., substN]), time(timerName), timeEnd(timerName), trace(), warn(obj1 [, obj2, ..., objN]), warn(msg [, subst1, ..., substN])
// "debug", "dir", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "time", "timeEnd", "trace", "warn"
// Chrome (2013. 01. 25.): https://developers.google.com/chrome-developer-tools/docs/console-api
// assert(expression, object), clear(), count(label), debug(object [, object, ...]), dir(object), dirxml(object), error(object [, object, ...]), group(object[, object, ...]), groupCollapsed(object[, object, ...]), groupEnd(), info(object [, object, ...]), log(object [, object, ...]), profile([label]), profileEnd(), time(label), timeEnd(label), timeStamp([label]), trace(), warn(object [, object, ...])
// "assert", "clear", "count", "debug", "dir", "dirxml", "error", "group", "groupCollapsed", "groupEnd", "info", "log", "profile", "profileEnd", "time", "timeEnd", "timeStamp", "trace", "warn"
// Chrome (2012. 10. 04.): https://developers.google.com/web-toolkit/speedtracer/logging-api
// markTimeline(String)
// "markTimeline"
assert: noop, clear: noop, trace: noop, count: noop, timeStamp: noop, msIsIndependentlyComposed: noop,
debug: log, info: log, log: log, warn: log, error: log,
dir: log, dirxml: log, markTimeline: log,
group: start('group'), groupCollapsed: start('groupCollapsed'), groupEnd: end('group'),
profile: start('profile'), profileEnd: end('profile'),
time: start('time'), timeEnd: end('time')
};
for (var method in methods) {
if ( methods.hasOwnProperty(method) && !(method in console) ) { // define undefined methods as best-effort methods
console[method] = methods[method];
}
}
})();
Try
if (!window.console) console = ...
未定义的变量不能直接引用。但是,所有全局变量都是全局上下文(浏览器为窗口)同名的属性,访问未定义的属性是可以的。
或者使用if (typeof console === 'undefined') console =…如果你想避开神奇的变量窗口,请参阅@Tim Down的回答。