Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I have multiple service workers both intercept the same fetch request?

I'm writing a library which I will provide for 3rd parties to run a service worker on their site. It needs to intercept all network requests but I want to allow them to build their own service worker if they like.

Can I have both service workers intercept the same fetches and provide some kind of priority/ordering between them? Alternatively is there some other pattern I should be using?

Thanks

like image 490
owencm Avatar asked Mar 14 '16 23:03

owencm


People also ask

Can a page have multiple service workers?

This means that its possible have multiple Service Workers running on the same page, but on different scopes! If a Service Worker would have a unique identifier, it would be the combination of the origin domain plus the scope path.

Can I use fetch in service worker?

Service Workers are a special type of Web Worker with the ability to intercept, modify, and respond to all network requests using the Fetch API. Service Workers can access the Cache API, and asynchronous client-side data stores, such as IndexedDB , to store resources.

Can service workers access cache?

Using a Service worker you can easily set an app up to use cached assets first, thus providing a default experience even when offline, before then getting more data from the network (commonly known as Offline First).

What can service workers do that web workers Cannot?

Service workers are a proxy between the browser and the network. By intercepting requests made by the document, service workers can redirect requests to a cache, enabling offline access. Web workers are general-purpose scripts that enable us to offload processor-intensive work from the main thread.


1 Answers

No, you can not. Only one service worker per scope is allowed to be registered so the latest kick the previous one out unless the scope is more specific, in this case, the request is attended by the most specific only.

Nevertheless, you can attach multiple fetch handlers and they all will process the request so maybe you can write your functionality in a separated script and let the user's service worker to include your file via importScripts().

The first handler calling event.respondWith() synchronously (actually, you can not call this method asynchronously) wins and the remaining handlers trying to call will throw.

Prioritization and coordination requires middleware. You can check ServiceWorkerWare or sw-toolbox.

like image 132
Salva Avatar answered Oct 10 '22 09:10

Salva