DEV Community

Discussion on: Service workers and caching strategies explained

Collapse
 
martinrojas profile image
martin rojas

Thank you for adding that section. I had done some research and wanted to tweak your code a bit. Currenthing the registration.unregister() throws and error because registration is never defined. So this is what I have ended up using.

// Unregister the service worker
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.getRegistrations().then(function (registrations) {
    for (let registration of registrations) {
      //unregister service worker for old domain
      registration.unregister()
    }
  }).catch(function (err) {
    // fail state, which is fine as we just don't want a service worker.
    console.log('Fail: ', err);
  });
}

caches.keys()
    .then(keys =>
        Promise.all(keys.map(async key => await caches.delete(key))))
    .catch((err) => console.error('Something went wrong: ', err));

Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
paco_ita profile image
Francesco Leardini

Yeah, you need to invoke the code within the registration "scope", as you need it to invoke the unregister method.