[w3c/ServiceWorker] Add auto claim option to register() (Issue #1661)

Currently if a first page load wants to register a service worker and immediately be controlled by it it has to do quite a bit of boilerplate:

```js
// serviceworker.js
self.addEventListener('activate', (event) => {
  event.waitUntil(clients.claim());
});
```

```js
// main.js
async function registerServiceWorker() {
  await navigator.serviceWorker.register('serviceworker.js');
  const registration = await navigator.serviceWorker.ready;
  const worker = registration.active;
  if (worker.state === 'activated') {
    return;
  }
  await new Promise(resolve => {
    worker.addEventListener('statechange', () => {
      if (worker.state = 'activated') {
        resolve();
      }
    });
  });
}
```


We could simplify this by adding a new option to register that does the same thing (including the SW side) and reduce all this down to:
```js
// main.js
await navigator.serviceWorker.register('serviceworker.js', { claim: true });
```

-- 
Reply to this email directly or view it on GitHub:
https://github.com/w3c/ServiceWorker/issues/1661
You are receiving this because you are subscribed to this thread.

Message ID: <w3c/ServiceWorker/issues/1661@github.com>

Received on Monday, 14 November 2022 04:22:36 UTC