I am trying to create a Chrome extension that adds a panel to the DevTools console.
The extension will have permission to interact with all urls, so to respect my users, I want to ensure that nothing is running when the devtools panel is closed.
The only thing the DevTool panel needs from the attached page (and all of its iframes) is to listen to a custom event dispatched on the respective window (could also be a postMessage
)
window.addEventListener('my-custom-event', e => console.log(e.detail))
I understand that you cannot attach listeners directly from the DevTools panel onto the page/frames and you need a content_script
to shuttle the messages forward (as described here).
The issue is, the content_script
is always appended to the page regardless of whether the panel is open or not. It sets a listener and basically doesn't run unless the listener transfers a port to communicate on.
I would feel irresponsible knowing that my content script runs on every page, potentially impacting the performance of that page so I'd like them to only be attached to the page when the devtools panel is open and the page reloaded.
Ideally I would like to implement a "recording" button which, only when enabled, the content_script
is added to the page. This is to avoid noise when doing performance profiling.
So my question is:
- Can you inject
content_script
only when the DevTools panel is open and
- Are you able to programmatically toggle
content_script
injection?