0

I am writing a chrome extension where a background task will be started when the user clicks a button. The task will regularly send a GET request to check some variable. Then the user can stop the task by clicking another button.

This is the first time I work with chrome extension, so the first idea was to use web workers, but it seems that Chrome does not allow loading local files for workers.

Is there another way to do it ?

Spider
  • 875
  • 2
  • 9
  • 27
  • You need a [background script](https://developer.chrome.com/extensions/background_pages). See also the [overview](https://developer.chrome.com/extensions/overview). – wOxxOm Apr 19 '20 at 10:42
  • @wOxxOm as I understood, background script is for the page event listeners. What I am looking for is like a webworker, a kind of thread executing in the background, triggered by a button in the popup, and stopped with another button. – Spider Apr 20 '20 at 14:50
  • @wOxxOm can you explain how would you do it ? – Spider Apr 20 '20 at 14:57
  • 2
    In short, the popup will send a message, your background script will receive it in [onMessage listener](https://developer.chrome.com/extensions/messaging). The background script runs in a hidden separate background page where you can do your stuff, spawn web workers if needed, anything. If you declare the background script with `"persistent":false` see also [Persistent background page on demand or an event page that doesn't unload?](https://stackoverflow.com/a/58577052) – wOxxOm Apr 20 '20 at 14:59
  • @wOxxOm thank you. I am getting to the same problem, webworkers are not anymore allowed with chrome extension, and executing a code with an infinite loop blocks the popup. – Spider Apr 20 '20 at 15:49
  • Web workers are perfectly allowed in chrome extensions, you simply need to use a script that's inside the extension directory. It won't be a `file` URL. It'll be a path e.g. `/script.js` – wOxxOm Apr 20 '20 at 15:50
  • Also, depending on the goal, you can do everything in the background script, without any workers. – wOxxOm Apr 20 '20 at 16:02

0 Answers0