DARK_DUCK
DARK_DUCK

Reputation: 1777

Updating a ServiceWorker only for new clients

I'm trying to make the update of my ServiceWorker work.

I have an old service worker, some windows are under it's control. Now there is a new version of the ServiceWorker. It get installed properly. But it does not get activated for new pages. My aim is to keep the old one for old pages and the new for every new tab/pages viewed.

Any idea how to accomplish this ?

Edit:

Is how I check that the the new service worker is not updated:

I have a sendMessage method:

sendMessage(message): Promise {
    const channel = new MessageChannel();
    const p1 = channel.port1;
    const result = new Promise(resolve => {
      p1.onmessage = ({ data }) => {
        resolve(data);
      };
    });
    serviceWorker.controller.postMessage(message, [channel.port2]);
    return result;
  }

Then I use it to check on page start

this.ready = this.sendMessage('version')
  .then(version => {
    if (version !== process.env.BUILD_NUMBER) {
      console.log('$$ Version mismatch, reinstalling service worker');
      throw new Error('build mismatch');
    }

    return serviceWorker.controller;
   });

And I answer in the ServiceWorker

self.addEventListener('message', ({ data, ports  }) => {
  const client = ports[0];
  if (data === 'version') {
    client.postMessage(process.env.BUILD_NUMBER);
  }
});

Edit

Adding:

event.waitUntil(self.clients.claim());

helps but it activate the ServiceWorker also for old clients.

Thanks

Upvotes: 0

Views: 343

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56044

Calling self.skipWaiting() within a service worker's install event handler will cause the newly installed service worker to immediately activate, even if there's an existing, older service worker that's currently active for other clients. Without self.skipWaiting(), the newly installed service worker will remain in a waiting state until all other clients of the previous service worker have been closed.

Calling self.clients.claim() from inside the activate event handler is sometimes used as well, but only if you want the newly activated service worker to take control of already-open clients that are either uncontrolled, or controlled by an older version of the service worker. In your case, it sounds like you do not want that behavior, so you shouldn't call self.clients.claim().

Upvotes: 1

Related Questions