Chrome: Get active tab console output?

前端 未结 1 1928
轻奢々
轻奢々 2021-01-15 13:07

I\'m creating a custom Chrome extension, which is going to retrieve data about an active tab before sending it to a secondary website.

I\'ve been trying to find a me

相关标签:
1条回答
  • 2021-01-15 13:23

    This issue is significantly harder than it appears.

    APIs like chrome.tabs have no access to a tab's console. In fact, no "standard" API does.

    One could expect a content script running in the context of the page to be able to access it. However, there's no way to access previous output of the console from a JavaScript context.

    The method you quote in your update (creating wrappers around console.* functions) can only capture future invocations of those functions, and won't capture things like errors from the JS runtime itself (e.g. unhandled exceptions or network errors). As such, to access console from an arbitrary tab, you'll need to inject this code into every tab, before it loads, even if you only rarely use it.

    It is further complicated by the fact that content scripts do not, in fact, run in the same context. To override console for the page itself, you'll need to inject the script in the page context.

    So, to summarize:

    1. You can do it by overriding console.* functions and listening to error event on window object, but it has to be done in page context by a document_start content script injecting code into every page. Extracting this data from the page context will be a challenge in itself.

      Downsides:

      • It hurts overall browser performance.
      • It won't see some browser-initiated messages that go directly to console.
    2. You can take the big hammer and use chrome.debugger API. This API has the same level of access to the page as the Dev Tools themselves - therefore, it's possible to obtain the full console output history.

      Downsides:

      • You'll need to study the remote debugging protocol, see the official examples.
      • A very scary warning will be shown in all tabs when the debugger API is used.

    All in all, what you're trying to achieve is a hard task with fragile solutions. Perhaps you need to rethink your approach.

    0 讨论(0)
提交回复
热议问题