Service Worker: WindowClient.navigate() Sample

Available in Chrome 49+ | View on GitHub | Browse Samples

Background

WindowClient.navigate() allows a service worker to cause a web page to navigate to a specific URL.

This sample shows how WindowClient.navigate() can be called within a service worker's activate handler, to navigate to activated.html. If your browser supports service workers, and supports WindowClient.navigate(), then you'll be automatically navigated away from this page once the service worker activates.

Note that the activate event is only fired once per version of a given service worker registration. If you'd like to trigger it again to test out the WindowClient.navigate() behavior, you can revisit this page in a Chrome Incognito window, which will trigger a fresh service worker registration.

This Page's JavaScript

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('service-worker.js');
}

Service Worker's JavaScript

self.addEventListener('activate', event => {
  event.waitUntil(self.clients.claim().then(() => {
    // See https://developer.mozilla.org/en-US/docs/Web/API/Clients/matchAll
    return self.clients.matchAll({type: 'window'});
  }).then(clients => {
    return clients.map(client => {
      // Check to make sure WindowClient.navigate() is supported.
      if ('navigate' in client) {
        return client.navigate('activated.html');
      }
    });
  }));
});