这是我对各种答案的看法。我想实际查看记录的消息,即使在它们被触发时我没有打开 IE 控制台,所以我将它们推送到我创建的 console.messages 数组中。我还添加了一个函数console.dump(),方便查看整个日志。 console.clear() 将清空消息队列。
此解决方案还“处理”其他控制台方法(我相信它们都源自Firebug Console API)
最后,这个解决方案是IIFE的形式,所以它不会污染全局范围。回退函数参数在代码底部定义。
我只是将它放在我的主 JS 文件中,该文件包含在每个页面上,然后忘记它。
(function (fallback) {
fallback = fallback || function () { };
// function to trap most of the console functions from the FireBug Console API.
var trap = function () {
// create an Array from the arguments Object
var args = Array.prototype.slice.call(arguments);
// console.raw captures the raw args, without converting toString
console.raw.push(args);
var message = args.join(' ');
console.messages.push(message);
fallback(message);
};
// redefine console
if (typeof console === 'undefined') {
console = {
messages: [],
raw: [],
dump: function() { return console.messages.join('\n'); },
log: trap,
debug: trap,
info: trap,
warn: trap,
error: trap,
assert: trap,
clear: function() {
console.messages.length = 0;
console.raw.length = 0 ;
},
dir: trap,
dirxml: trap,
trace: trap,
group: trap,
groupCollapsed: trap,
groupEnd: trap,
time: trap,
timeEnd: trap,
timeStamp: trap,
profile: trap,
profileEnd: trap,
count: trap,
exception: trap,
table: trap
};
}
})(null); // to define a fallback function, replace null with the name of the function (ex: alert)
一些额外的信息
var args = Array.prototype.slice.call(arguments); 行从arguments 对象创建一个数组。这是必需的,因为arguments is not really an Array。
trap() 是任何 API 函数的默认处理程序。我将参数传递给message,以便您获得传递给任何API 调用(不仅仅是console.log)的参数的日志。
编辑
我添加了一个额外的数组console.raw,它完全按照传递给trap() 的方式捕获参数。我意识到args.join(' ') 正在将对象转换为字符串"[object Object]",这有时可能是不可取的。感谢bfontaine 提供suggestion。