Search code examples
service-workerprogressive-web-appsworkbox

Keep the precache while deleting other cache in workbox service worker


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);
});

Solution

  • 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);
    });