Search code examples
webservice-workerweb-worker

Can a service worker intercept http requests coming from a web worker?


I know that service workers can intercept http request coming from the UI/Main thread. I would like to know whether the service worker can intercept http request coming from the Worker Threads (web worker). The reason for this is to enable retries and recovery for when the Tab/Browser is eventually destroyed or stopped by the user or the Operating system.


Solution

  • Yes, something created by new Worker(workerSrcUrl) can be a client of a service worker, and a service worker's fetch event listener can respond to network requests initiated inside of the Worker.

    You should note a few things:

    • There is an upcoming change, currently planned for Chrome/Edge 93, to resolve some non-compliant behavior around Clients.matchAll({type: 'worker'}) and how scoping is applied. More details can be found in this status entry.

    • A Worker can't actually outlive the tab or browser that started it, so creating a Worker is not going to allow you to run code that will continue outside of the lifetime of the browser's tab that created it.