0

I have a simple use case, where I am writing a Chrome extension that adds a panel to the browser devtools which acts as a visualization for data emitted from the host page.

As an analogy, imagine the host page emits a message on an interval

setInterval(() => window.postMessage('Hi'), 1000)

Ideally, I want to have a devtools panel that simply logs the events.

// This is invalid, there is no `addEventListener`
chrome.devtools.inspectedWindow.addEventListener('message', (msg) => {
  console.log(msg)
})

According to this: https://developer.chrome.com/docs/extensions/mv3/devtools/#solutions there is no way to have a devtools extension access the attached page directly.

Messages must be forwarded, first from the content_script to the background service_worker, then from the service_worker to the devtools_page.

This is a bit of a journey but it's fine - my issue is - the background service_worker and content_script will always be injected into every page, regardless of whether the devtools panel is open or not.

Having this background process running on all pages all the time on is wasteful and I would like to avoid it.

Is there:

a) A way to talk directly to the page from the devtools panel?

b) A way to only run the service_worker and content_script if the devtools panel is open?

David Alsh
  • 6,747
  • 6
  • 34
  • 60
  • a) If you know the tabId, you can use tabs.sendMessage. b) Implement processing ON/OFF logic in the service worker and control it from DevTools with runtime.sendMessage. – Norio Yamamoto Feb 14 '23 at 05:34
  • With a) can you send a message from the tab to the attached panel? – David Alsh Feb 14 '23 at 05:39
  • I could maybe try buffering and polling using the scripting API? – David Alsh Feb 14 '23 at 06:48
  • In addition to the linked [communication example](https://stackoverflow.com/a/72902614) you can also use chrome.scripting.executeScript (in devtools_page) to inject the content script(s) when devtools panel is open instead of declaring them in manifest.json. See also [detect if Chrome extension content script has been injected / content script include guard](https://stackoverflow.com/a/18423519) – wOxxOm Feb 14 '23 at 10:42

0 Answers0