0

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

pan
  • 1
  • 1
  • Simply use messaging with scripting. 1) `scripting` doesn't add any permission warnings so you can safely use it. 2) If `chrome` doesn't exist in a content script for you it means you've explicitly specified the unsafe `"world": "MAIN"`, which you shouldn't generally do, so just remove it. If you really need it then you'll have to use a second content script in default world which can communicate via `chrome`, these two scripts can communicate via CustomEvent. 3) Indeed content scripts can't receive data from a cross-origin URL. – wOxxOm Aug 20 '23 at 05:49
  • @wOxxOm thank you for your guidance, your second tip works perfect – pan Aug 20 '23 at 11:09

1 Answers1

0

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

  • first one (without specified "world" property) to run WebSocket;
  • second one in "world": "MAIN" to work with page api;

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.

pan
  • 1
  • 1