How to clear a service worker’s cache?

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

The problem is that when I change JS, this change is not displayed directly in the client browser. Of course, in hrome dev-tools I can disable the cache. But in chrome mobile, how do I do this?

I tried to access the site settings and press the CLEAR% RESET button. But it still loads the old page / cache loading. I tried using a different browser or chrome incognito and it loads a new page.

Then I try to clear the browser data (cache only) and it works.

I think that is not how it should work correctly? my user will not know if the page is refreshing without clearing the cache of the Chrome browser.

+8
javascript html google-chrome service-worker
source share
2 answers

Use this to remove obsolete 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); }) ); }) ); }); 
+10
source share

the other answer is a bit detailed and does a lot more than necessary, and given its complete lack of explanation, it takes a bit of parsing on behalf of the user so that they change it to what works for them. So here it’s easier

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

 caches.delete(/*name*/); 

And if you want to erase all caches (and not wait for them, let's 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); }); 
+15
source share

All Articles