vite-pwa / vite-plugin-pwa

Zero-config PWA for Vite
https://vite-pwa-org.netlify.app/
MIT License
3.23k stars 211 forks source link

Add event when updated worker is ready #352

Open rogerfar opened 2 years ago

rogerfar commented 2 years ago

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 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

userquin commented 2 years ago

@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).

userquin commented 2 years ago

@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.