A Computer Polyglot, CLI + WEB ♥'r.

URL Navigation From Service Worker

| Comments

Given that the service worker has only readonly access to the navigator.location it is not possible to change the location from within the service worker, but with WindowClient.navigate API it is easy to do a navigation!

The navigate() method of the WindowClient interface loads a specified URL into a controlled client page then returns a Promise that resolves to the existing WindowClient.

Say, you want to navigate to a particular URL (/meow.html in this case ;)) after the service worker is activated, you could something like:

self.addEventListener('activate', event => {
  event.waitUntil(self.clients.claim().then(() => {
      returns a Promise for a list of service worker clients.
      type could be: window, worker, sharedworker or all.
    return self.clients.matchAll({type: 'window'});
  }).then(clients => {
    return clients.map(client => {
      // `WindowClient.navigate()` is not yet supported in all the browser.
      if ('navigate' in client) {
        return client.navigate('meow.html');

Hope with this it's clear now on how a service worker can navigate the clients it controls to a given URL.

Happy navigating! ;)

Update: Directly from the spec:

The navigate() method must run these steps or their equivalent:

  • Let url be the result of parsing url with entry settings object's API base URL.

  • If url is failure, return a promise rejected with a TypeError.

  • If url is about:blank, return a promise rejected with a TypeError.

  • If the context object's associated service worker client's active worker is not the incumbent settings object's global object's service worker, return a promise rejected with a TypeError.

  • Let promise be a new promise.

  • Run these steps in parallel:

    • Let browsingContext be the context object's associated service worker client's global object's browsing context.

    • If browsingContext has discarded its Document, reject promise with a TypeError and abort these steps.

    • Queue a task to run the following substeps on the context object's associated service worker client's responsible event loop using the user interaction task source:

      • Navigate browsingContext to url with replacement enabled and exceptions enabled. The source browsing context must be browsingContext.

      • If the navigation throws an exception, reject promise with that exception and abort these steps.

      • If the origin is not the same as the service worker's origin, then:

        • Resolve promise with null.

        • Abort these steps.

      • Let client be the result of running Capture Window Client algorithm, or its equivalent, with browsingContext as the argument.

      • Resolve promise with client.

  • Return promise.