Provide a one-line way to listen for a waiting Service Worker
Nobody has claimed this yet.
- Dominant language
- Bikeshed
- Stars
- 3.6k
- Forks
- 324
- Avg merge
- 14d 22h
- Merged PRs (30d)
- 1
Description
It's a common use case to pop up a notification to end users when a new Service Worker is waiting, but it's inconvenient to listen for that event.
ServiceWorkerRegistration offers an onupdatefound event, but that fires when the new Service Worker is detected and installation has started, not when the new Service Worker is fully installed and waiting to take control. In other words, it notifies us when registration.installing changes, but not when registration.waiting changes.
It's still possible to await a change in registration.waiting by attaching a listener to the onstatechange event of the .installing Service Worker, and to wait for an .installing Service Worker by waiting for the onupdatefound event of the registration itself, like this:
function listenForWaitingServiceWorker(reg, callback) {
function awaitStateChange() {
reg.installing.addEventListener('statechange', function() {
if (this.state === 'installed') callback(reg);
});
}
if (reg.waiting) return callback(reg);
if (reg.installing) awaitStateChange();
reg.addEventListener('updatefound', awaitStateChange);
}
This function gets its own special quiz in the Udacity "Offline Web Applications" course; it seems like this cow path could be paved.
I propose adding a .waiting Promise on the ServiceWorkerContainer, and/or an onwaiting event to ServiceWorkerRegistration. I'd love a one-liner like this:
navigator.serviceWorker.waiting.then(alertUser);
Combined with #1016, you could write code like this:
navigator.serviceWorker.addEventListener('controllerchange', () => window.location.reload());
navigator.serviceWorker.waiting.then(reg => {
if (confirm('refresh now?')) reg.waiting.skipWaiting();
});
(Uh, don't actually use confirm() in production; it's just convenient for this example.)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the ServiceWorkerContainer and ServiceWorkerRegistration entry points described in the issue, comparing the existing onupdatefound and onstatechange behavior with the proposed waiting Promise or onwaiting event. The work is done when the project agrees on one API shape and the corresponding Service Worker specification behavior is defined.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript
- Domain
- api, web-dev
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 25/100