javascriptgoogle-chrome-extensionircchrome-extension-manifest-v3twitch-api

Chrome extension manifest v3; Is there a way to communicate between background service_worker and content_scripts?


I have service_worker at background that is running WebSocket connection with twitch chat. Also I have content_script that is connected to music service api, handling events of current track change. And I need to extract data from content_script (current track info) and use it inside service_worker script when WebSocket receiving message with data request.

Is there any chance to do my task with minimal usage of different manifest permissions?

Important: manifest v3 required

I know that I can use chrome.scripting.executeScript to inject utility script that is able to handle chrome.runtime.onMessage from background and let my content_script serving api know about data request with window.dispatchEvent but I dont want to use permissions: ["scripting"] and I can't just directly use chrome.runtime.onMessage because chrome context does not exist at content_script that is set by manifest properties.

Also I could run my WebSocket at content_script but it refuses connection with error my_content_script_name.js:37 Refused to connect to 'wss://irc-ws.chat.twitch.tv:413/' because it violates the following Content Security Policy directive: [...] and I can't do anything with that through manifest rule content_security_policy because Chrome fires error 'content_security_policy.extension_pages': Insecure CSP value


Solution

  • According to @wOxxOm comment (thanks), need to use two content_scripts:

    To communicate between them we can use CustomEvent, window.dispatchEvent and window.addEventListener. So for now when script #1 with WebSocket receiving specific command message I can dispatch event requesting data from script #2.