0

All I want is a single Web Worker shared by all tabs that doesn't get interrupted by page reloads, etc.. Can I simply use a Service Worker as a drop-in replacement to accomplish this? I don't care about caching or networking, only about message-passing (via onmessage) to offload certain computation to a background process, and perhaps also make notifications.

Sorry if this is a simple question. All I've seen is tutorials for caching and networking, involving installs, etc..

chausies
  • 765
  • 7
  • 20
  • Is this something you could offload to a server and use sockets to communicate with the various tabs? – charlietfl Jul 19 '20 at 03:22
  • It's not that I want my various tabs to communicate. It's just that I want it so that more than 1 worker isn't opened by all the tabs. Also, I want everything running locally, not on a server. Finally, the main thing I want is persistence through page reloads (which web workers and shared workers don't have). – chausies Jul 19 '20 at 13:59

1 Answers1

0

This sounds more like a job for a SharedWorker instead, even if for the "notifications" thing, if it's indeed just a way for your tabs to all communicate together, then you could accomplish it more easiliy with a BroadcastChannel.

Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • SharedWorkers do NOT persist through reloads/refreshes (https://stackoverflow.com/a/11906338/1114253), which is the main reason I wanted to use a service worker. Also, it's not that I want to allow the tabs to communicate, so much as I just want only one worker running, no matter how many tabs are open. – chausies Jul 19 '20 at 14:01
  • 1
    They do as long as a context keeps them alive, like [ServiceWorker's context](https://stackoverflow.com/questions/34775105/what-causes-the-global-context-of-a-service-worker-to-be-reset) If you need to persist data, then use localStorage or IndexedDB – Kaiido Jul 19 '20 at 14:14
  • Thank you, that's illuminating. So if I used `setInterval` inside a Shared Worker, it would keep going so long as at least 1 tab keeps the worker alive, yes? Also, persistent data isn't my problem. I'm just trying to make a progressive web app, and want some worker always in the background doing something. – chausies Jul 19 '20 at 14:50