1

I am using below code to purge workbox created cache but it also deletes the precache which is managed by workbox it selves.

Please let me know if better way exists.

// Clean up caches in activate event to ensure no pages are using the old caches.
self.addEventListener('activate', (event) => {
    const promiseChain = caches.keys()
        .then((cacheNames) => {
            // Step through each cache name and delete it 
            return Promise.all(
                cacheNames.map((cacheName) => caches.delete(cacheName))
            );
        });

    // Keep the service worker alive until all caches are deleted.
    event.waitUntil(promiseChain);
});
Syed
  • 891
  • 2
  • 8
  • 29
  • Call delete on a single cacheName by temp remove of the "map" . See what result is – Robert Rowntree Feb 03 '20 at 09:13
  • Thank you @RobertRowntree for your time, I am not good in service worker programming, please write code in answer if your have more time. – Syed Feb 03 '20 at 09:18
  • review this answer : https://stackoverflow.com/questions/45467842/how-to-clear-cache-of-service-worker then see if you can use the map to do an enumerated list of your caches without delete. once u have list of cache names you can alter the code to filter on name, deleting ONLY the 1 cache from list. – Robert Rowntree Feb 03 '20 at 17:44

1 Answers1

1

Below piece of code works fine to delete other caches while keeping the precache in workbox service worker.

// Clear old caches
var clearOldCaches = function (event)
{
    event.waitUntil(
        caches.keys().then(function (cacheNames) {
            let validCacheSet = new Set(Object.values(workbox.core.cacheNames));
            return Promise.all(
                cacheNames
                .filter(function (cacheName) {
                    return !validCacheSet.has(cacheName);
                })
                .map(function (cacheName) {
                    return caches.delete(cacheName);
                })
            );
        })
    );
};

self.addEventListener("activate", function (event) {
    clearOldCaches(event);
});
Syed
  • 891
  • 2
  • 8
  • 29