Javascript 获取控制台历史
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13763361/
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
Get console history
提问by Fran?ois Beaufort
I'd like to know if there is a way in javascript to retrieve console history.
我想知道 javascript 中是否有一种方法可以检索控制台历史记录。
What I mean by console history is what appears in the dev tools console. For instance, I'd like to print in a html page all errors, warnings, info and log that are displayed in my dev tools without opening them.
我所说的控制台历史记录是出现在开发工具控制台中的内容。例如,我想在 html 页面中打印在我的开发工具中显示的所有错误、警告、信息和日志,而无需打开它们。
Let me know if I'm not clear.
如果我不清楚,请告诉我。
采纳答案by NVI
Chrome extensions had an API for that, experimental.devtools.console:
Chrome 扩展程序为此提供了一个 API,experimental.devtools.console:
chrome.experimental.devtools.console.getMessages(function(messages) { })
This API has been removed.
此 API 已被删除。
回答by Sander
I wrote a simple cross-browser library for this, called console.history. It's available on GitHub:
https://git.io/console
我为此编写了一个简单的跨浏览器库,名为console.history. 它可以在 GitHub 上找到:https:
//git.io/console
What the library basically does is catch all calls to console.[log/warn/error/debug/info]and store them in the console.historyarray. As a bonus, a full stack trace is also added.
该库的主要作用是捕获所有调用console.[log/warn/error/debug/info]并将它们存储在console.history数组中。作为奖励,还添加了完整的堆栈跟踪。
Test file test.jscontains:
测试文件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();
The entry to console.historywill be:
进入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"
}
}
回答by epascarello
There is no way to get the console data with JavaScript. Only way you would be able to do it is basically hiHyman all the console functions and store a copy and than call the default log lines.
无法使用 JavaScript 获取控制台数据。您能够做到的唯一方法基本上是劫持所有控制台功能并存储副本,然后调用默认日志行。
回答by Séverin
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);
}
}
And then use console.historyto access history
然后使用console.history访问历史

