我想知道javascript中是否有办法检索控制台历史记录。
我所说的控制台历史记录是指开发工具控制台中显示的内容。例如,我想在 html 页面中打印我的开发工具中显示的所有错误、警告、信息和日志,而无需打开它们。
如果我不清楚,请告诉我。
我为此编写了一个简单的跨浏览器库,称为console.history
。它在GitHub上可用:https://git.io/console
该库基本上所做的是捕获所有对console.[log/warn/error/debug/info]
的调用并将它们存储在 console.history
数组中。作为奖励,还添加了全栈跟踪。
测试文件test.js
包含:
function outer() {
inner();
}
function inner() {
var array = [1,2,3];
var object = {"foo": "bar", "key": "value"};
console.warn("Something went wrong, but we're okay!", array, object);
}
outer();
console.history
的条目将是:
{
"type": "warn",
"timestamp": "Thu, 01 Sep 2016 15:38:28 GMT",
"arguments": {
"0": "Something went wrong, but we're okay!",
"1": [1, 2, 3],
"2": {
"foo": "bar",
"key": "value"
}
},
"stack": {
"0": "at inner (http://localhost:1337/test/test.js:6:11)",
"1": "at outer (http://localhost:1337/test/test.js:2:3)",
"2": "at http://localhost:1337/test/test.js:9:1"
}
}
这是一种获取chrome控制台历史记录的方法(虽然不是javascript方式) -
- 在 DevTools 中,取消停靠到单独的窗口中(使用按 +移位+P)
- Ctrl+Shift+J to DevTool your DevTools
- 转到应用程序选项卡 ->本地存储 -> devtools://devtools
- 双击或编辑控制台历史记录的值,然后将其复制
参考: https://chema.medio.click/en/dev/reviewing-the-console-command-history-in-chromes-devtools/
Chrome扩展程序有一个API,experimental.devtools.console:
chrome.experimental.devtools.console.getMessages(function(messages) { })
此 API 已被删除。
无法使用 JavaScript 获取控制台数据。您能够做到这一点的唯一方法基本上是劫持所有控制台功能并存储副本,然后调用默认日志行。
console.history = [];
var oldConsole = {};
for (var i in console) {
if (typeof console[i] == 'function') {
oldConsole[i] = console[i];
var strr = '(function(){
console.history.push({func:'' + i + '',args : Array.prototype.slice.call(arguments)});
oldConsole['' + i + ''].apply(console, arguments);
})';
console[i] = eval(strr);
}
}
然后使用 console.history 访问历史记录