vite-plugin-pwa
vite-plugin-pwa copied to clipboard
Add event when updated worker is ready
Clear and concise description of the problem
At the moment when calling updateServiceWorker it calls SKIP_WAITING, but there are a few issues with this:
- The event does not do anything until the workbox event
waitingis fired, otherwise the worker will sit in waiting state forever. - There is no event passed back to the user indicating that the update is ready.
The issue is that our cache is fairly big (fully offline app) and phone users need a bit to update the cache, because there is no way of knowing that the new cache is activated, they reload the page too quickly and having to re-installed the service worker again.
Suggested solution
https://github.com/antfu/vite-plugin-pwa/blob/main/src/client/build/register.ts#L47
Wrap the messageSW in an event:
wb?.addEventListener('waiting', (event) => {
if (registration && registration.waiting) {
// Send a message to the waiting service worker,
// instructing it to activate.
// Note: for this to work, you have to add a message
// listener in your service worker. See below.
await messageSW(registration.waiting, { type: 'SKIP_WAITING' })
}
})
Add an event to the RegisterSWOptions: onUpdateReady, which is called when controlling:
https://github.com/antfu/vite-plugin-pwa/blob/main/src/client/build/register.ts#L42
wb?.addEventListener('controlling', () => {
onUpdateReady?();
});
I can create a PR if this feature seems legit.
Alternative
No response
Additional context
No response
Validations
- [X] Follow our Code of Conduct
- [X] Read the Contributing Guide.
- [X] Check that there isn't already an issue that request the same feature to avoid creating a duplicate.
@rogerfar there is no problem updating the cache, it is done by the browser in a background thread, if the app is large then it will take more time to be ready (check @vueuse for example).
If you call updateServiceWorker(false) (I don't know why you want to call it with false) you should do a hard refresh or reopen the browser, the sw will be updated (just try pressing F5 while the sw is in yellow state, then hard refresh). It seems all browsers with the exception of Safari will work (#33 is not reproducible anymore at least on Chromium based browsers and Firefox).
@rogerfar, on the other hand, we would be interested in being able to notify the user that a new version has been detected and is being downloaded, so PR welcome
EDIT: we can late discuss if we add it only when using prompt or also for auto update.