80

So, I have an HTML page with service worker, the service worker cache the index.html and my JS files.

The problem is when I change the JS, the change doesn't show up directly on the client browser. Of course in chrome dev-tools, I can disable cache. But in chrome mobile, how do I do that?

I tried to access the site settings and hit the CLEAR % RESET button. But it still loads the old page/load from cache. I tried to use other browser or chrome incognito and it loads the new page.

Then, I try to clear my browsing data (just cache) and it works.

I guess that's not how it should work right? my user won't know if the page is updated without clearing the chrome browser cache.

1

6 Answers 6

123

If you know the cache name you can simply call caches.delete() from anywhere you like in the worker:

caches.delete(/*name*/);

And if you wanted to wipe all caches (and not wait for them, say this is a background task) you only need to add this:

caches.keys().then(function(names) {
    for (let name of names)
        caches.delete(name);
});
6
  • 2
    Thanks for this. It is a lot simpler a clearer. I just wrote mine up quickly to answer the question
    – liam
    Oct 8, 2017 at 18:06
  • 2
    Nah no worries. Yours would be perfect if someone wanted to delete a specific set of caches within the activate listener; I just did this in case someone only wanted to dump one/everything
    – Hashbrown
    Oct 8, 2017 at 23:04
  • 4
    The most compact code is probably caches.keys().then(cs=>cs.forEach(c=>caches.delete(c))) or for async functions (await caches.keys()).forEach(c=>caches.delete(c)) Oct 26, 2017 at 12:03
  • where I live, You Mr. will be regarded a Mustache ! ( a compliment )
    – Khaledonia
    Jan 4, 2018 at 13:58
  • 1
    Note! You should check if caches exists. If you want to clear caches outside of the Service Worker check add something like if (!window.caches) return;. Also not that caches object might not exist on HTTP (e.g. in Chrome).
    – Nux
    Apr 20, 2018 at 15:00
45

Use this to delete outdated caches:

self.addEventListener('activate', function(event) {
  event.waitUntil(
    caches.keys().then(function(cacheNames) {
      return Promise.all(
        cacheNames.filter(function(cacheName) {
          // Return true if you want to remove this cache,
          // but remember that caches are shared across
          // the whole origin
        }).map(function(cacheName) {
          return caches.delete(cacheName);
        })
      );
    })
  );
});
7
  • 6
    What is self here? The window object or a serviceworker?
    – loopmode
    Sep 15, 2017 at 9:12
  • 62
    It's good practice on Stack Overflow to add an explanation as to why your solution should work. For more information read How To Answer.
    – Samuel Liew
    Oct 3, 2017 at 3:53
  • 3
    self means serviceWorker instance. :) Apr 2, 2018 at 7:54
  • 3
    self is a "SharedWorkerGlobalScope" object.
    – foxesque
    May 28, 2018 at 18:19
  • 1
    Using 'this' instead of 'self' can do the same same thing. But there's a difference between these two keywords. Apr 3, 2020 at 4:10
16

Typically you update the CACHE_NAME in your service workers JS file so your worker installs again:

self.addEventListener('install', evt => {
  evt.waitUntil(
    caches.open(CACHE_NAME).then(cache => cache.addAll(inputs))
  )
})

Alternatively, to clear the cache for a PWA find the cache name:

self.caches.keys().then(keys => { keys.forEach(key => console.log(key)) })

then run the following to delete it:

self.caches.delete('my-site-cache')

Then refresh the page.

If you see any worker-related errors in the console after refreshing, you may also need to unregister the registered workers:

navigator.serviceWorker.getRegistrations()
  .then(registrations => {
    registrations.forEach(registration => {
      registration.unregister()
    }) 
  })
4
  • 1
    last code: "navigator.serviceWorker....." helped me after removing superpwa wordpress plugin, to delete all cache related to service worker. Thanks
    – Vitalij
    Mar 17, 2020 at 7:57
  • 1
    Are the descriptive words above your code blocks 2 and 3 swapped?
    – David
    Aug 16, 2020 at 17:57
  • 1
    Thanks, David. Fixed with your help.
    – vhs
    Aug 19, 2020 at 10:53
  • Yes! It's not good enough to delete the service worker, you have to also unregister it! Yay! Dec 19, 2022 at 19:09
7

The most elegant solution, with async/await:

const cacheName = 'v2';

self.addEventListener('activate', event => {
// Remove old caches
  event.waitUntil(
    (async () => {
      const keys = await caches.keys();
      return keys.map(async (cache) => {
        if(cache !== cacheName) {
          console.log('Service Worker: Removing old cache: '+cache);
          return await caches.delete(cache);
        }
      })
    })()
  )
})
1
  • The service worker is installed in your browser. Your browser will request your remote worker every time (if online) and update its locally installed version for offline use. You can see which files get cached by printing it to console, i.e. console.log('Caching:', event.request.url) in your 'fetch' event after cache.put() Apr 27, 2021 at 17:57
1

This is the only code that worked for me. It is my adaptation of Mozilla documentation :

//Delete all caches and keep only one
const cachNameToKeep = 'myCache';

//Deletion should only occur at the activate event
self.addEventListener('activate', event => {
    var cacheKeeplist = [cacheName];
    event.waitUntil(
        caches.keys().then( keyList => {
            return Promise.all(keyList.map( key => {
                if (cacheKeeplist.indexOf(key) === -1) {
                    return caches.delete(key);
                }
            }));
        })
.then(self.clients.claim())); //this line is important in some contexts
});
2
  • 4
    cacheNameToKeep ?? [cacheName] ?? Are those both the same thing? What does self.clients.claim() do?
    – zipzit
    Oct 31, 2019 at 17:51
  • After activation, the service worker will now control pages, but only those that were opened after the register() is successful. In other words, documents will have to be reloaded to actually be controlled, because a document starts life with or without a service worker and maintains that for its lifetime. To override this default behavior and adopt open pages, a service worker can call self.clients.claim() Jul 19 at 8:06
0

I was so disperate until I decided to change the code in devtools directly.
This may not clear the cache and replace the file, but at least, it will let you debug the code until you find the perfect way to do that.
Another notice is that closing browser entirly and reopeing your page may help, but this is still a bad practice for debugging!

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.