【问题标题】:Get console history获取控制台历史记录
【发布时间】:2017-07-04 16:55:25
【问题描述】:

我想知道 javascript 中是否有办法检索控制台历史记录。

我所说的控制台历史是指出现在开发工具控制台中的内容。 例如,我想在一个 html 页面中打印我的开发工具中显示的所有错误、警告、信息和日志,而无需打开它们。

如果我不清楚,请告诉我。

【问题讨论】:

  • whathaveyoutried.com?这应该在网站上运行还是作为浏览器插件运行?你的目标浏览器是什么?请将此信息添加到您的问题/标签中。
  • 详细解释您要做什么。只有这样我们才能帮助您。

标签: javascript google-chrome-devtools


【解决方案1】:

我为此编写了一个简单的跨浏览器库,名为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"
  }
}

【讨论】:

  • 不错,但它不会在浏览器控制台中记录任何直接调用
【解决方案2】:

Chrome 扩展程序有一个 API,experimental.devtools.console

chrome.experimental.devtools.console.getMessages(function(messages) {  })

此 API 已被移除。

【讨论】:

  • 链接已失效,chrome.experimental => undefined
  • “实验”是操作词
  • 我希望有别的方法或方法可以达到相同的结果..
【解决方案3】:

无法使用 JavaScript 获取控制台数据。您能够做到的唯一方法基本上是劫持所有控制台功能并存储副本,然后调用默认日志行。

【讨论】:

    【解决方案4】:
    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 访问历史记录

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 1970-01-01
      • 2011-11-16
      • 2016-01-13
      • 1970-01-01
      相关资源
      最近更新 更多