Hemanth's Scribes

web

URL Navigation from Service Worker

Author Photo

Hemanth HM

Thumbnail

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
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.