如何使用 Chrome 浏览器扩展程序来监控和解析 devtools 控制台中的输出?

How can I use a Chrome browser extension to monitor and parse the output in the devtools console?

我正在构建一个 chrome 扩展,它应该有助于调试在网站上运行的软件。该软件可以启用调试模式,使用 console.log.

会导致大量输出到控制台

我想使用我的 chrome 扩展来解析控制台消息并在 UI 中显示重要事件以加快调试速度。但是,我没有看到用 the API 简单地做到这一点的方法。有什么我想念的吗?我应该重写 console.log 函数吗?我该怎么做?

有两种方法。

  • 覆盖 console.log、console.warn 等,在 page context (this is important!). There are lots of examples (here's a random one). In your case it'll be even simpler as you'll just call the original method and transfer the arguments via CustomEvent to your content script (example) 中,这将累积它们。
  • 使用chrome.debugger API with Console.messageAdded or Runtime.consoleAPICalled个事件。这将在整个浏览器中显示一个关于调试器处于活动状态的消息栏,除非你通过 运行 chrome 和 --silent-debugger-extension-api 命令行将其全局隐藏,但如果你不小心安装了恶意扩展,这有点危险使用 chrome.debugger API.