w3c / w3c/ServiceWorker

Add claim option to register()

Open
#1,661 0 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Bikeshed
Stars
3.6k
Forks
324
Avg merge
14d 22h
Merged PRs (30d)
1

Description

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:

// serviceworker.js
self.addEventListener('activate', (event) => {
  event.waitUntil(clients.claim());
});
// 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:

// main.js
await navigator.serviceWorker.register('serviceworker.js', { claim: true });

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the navigator.serviceWorker.register() entry point and compare the serviceworker.js and main.js examples in the issue. Determine the API behavior required for { claim: true }, including the service-worker-side activation and claiming flow. Done means the option provides the described immediate-control behavior without the shown boilerplate.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript
Domain
web-dev
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.