这是我从不同来源汇总的解决方案。它捕获了控制台中显示的大部分内容(有些无法捕获)。
它在console.everything 中以数组形式提供,其中包含类型、时间戳和发送到控制台的数据。
最好将其作为第一个脚本包含在其自己的 <script> 标记中,以确保它在其他任何内容之前运行并且不受稍后运行的代码的影响。
if (console.everything === undefined) {
console.everything = [];
function TS(){
return (new Date).toLocaleString("sv", { timeZone: 'UTC' }) + "Z"
}
window.onerror = function (error, url, line) {
console.everything.push({
type: "exception",
timeStamp: TS(),
value: { error, url, line }
})
return false;
}
window.onunhandledrejection = function (e) {
console.everything.push({
type: "promiseRejection",
timeStamp: TS(),
value: e.reason
})
}
function hookLogType(logType) {
const original= console[logType].bind(console)
return function(){
console.everything.push({
type: logType,
timeStamp: TS(),
value: Array.from(arguments)
})
original.apply(console, arguments)
}
}
['log', 'error', 'warn', 'debug'].forEach(logType=>{
console[logType] = hookLogType(logType)
})
}