NoobCoder
NoobCoder

Reputation: 615

Is it possible to multiple service workers run at the same time and handle different or same event types?

There is a lot of information over the internet and also here on Stackoverflow, but I'm still confused and be glad to get some clarifications. I have read:

and more (including Firebase docs, MDN docs).

My questions are:

What happens when I register 2 service workers for the same scope?

if ('serviceWorker' in navigator) {
        navigator.serviceWorker.register('/sw1.js', {scope: '/'})
            .then(registration => {
                console.log('sw1 registered with scope:', registration.scope);
            })
            .catch(error => {
                console.error('sw2 registration failed:', error);
            });
        navigator.serviceWorker.register('/sw2.js', {scope: '/'})
            .then(registration => {
                console.log('sw2 registered with scope:', registration.scope);
            })
            .catch(error => {
                console.error('sw2 registration failed:', error);
            });
    }

Lets call them sw1.js:

self.addEventListener("push", (event) => {

and sw2.js:

self.addEventListener("notificationclick", (event) => {

I understand that the last one that got registered is the one that becomes active and take charge of the scope. So - does it mean the first one, sw1 has no "power" at all?

Let me explain: if sw1 handles push events while sw2 handles onclickNotifications events, and sw2 is registered after sw1, does it mean that when a push event will be received, nothing will be handled since sw2 is now in charge and has no logic of handling push events?

Is there any event bubbling that "passes" the event to the other service worker in case it's not handled in the first one?

In case the answer is yes, that there is sort of "event bubbling" that passes the event to the other service worker if event handling is missing, can you "skip" an event by purpose in case you don't want to handle it in sw1 so it will be handled in sw2?

What I mean is if both service workers handle the same event types, lets say push events, but I want sw1 handle only push events that contain the title "Oh, Hi Mark", can I "skip" it so it will be handled by sw2?

Upvotes: 1

Views: 373

Answers (0)

Related Questions