Hemanth's Scribes

web

URL Navigation from Service Worker

Author Photo

Hemanth HM

Since service workers have readonly access to navigator.location, use WindowClient.navigate for navigation.

self.addEventListener('activate', event => {
  event.waitUntil(
    self.clients.claim()
      .then(() => self.clients.matchAll({ type: 'window' }))
      .then(clients => {
        return clients.map(client => {
          if ('navigate' in client) {
            return client.navigate('meow.html');
          }
        });
      })
  );
});

The navigate() method returns a Promise that resolves to the existing WindowClient.

Happy navigating! 🧭

#javascript#service-worker