[SOLVED] Why is the cache storage in Google Chrome developer tools empty in offline mode? – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by Deeksha Mulgaonkar

I am using service worker in order to cache and fetch the files.
The files are getting cached in online mode but when I shift to offline mode the cache storage in chrome developer tool is empty. I am not able to make out what is the issue.
Any help is appreciated.

const cacheName = 'myCacheVersion1';
var filesToCache = [
    '/',
    '/service-worker/offline-page.html',
    '/service-worker/sw.js'
]

const offlineUrl = 'https://gmc-test.mytrah.com/service-worker/offline-page.html';

this.addEventListener('install', event => {
    event.waitUntil(
        caches.open(cacheName).then(function(cache){
            console.log(offlineUrl);
            return cache.addAll(filesToCache);
        })
            .then(() => self.skipWaiting())
    );
})

self.addEventListener('activate', function(e) {
    console.log('[ServiceWorker] Activate');
    e.waitUntil(
        caches.keys().then(function(keyList) {
            return Promise.all(keyList.map(function(key) {
                if (key !== cacheName) {
                    console.log('[ServiceWorker] Removing old cache', key);

                    return caches.delete(key);
                }
            }));

        })
    );
    return self.clients.claim();
});

this.addEventListener('fetch', event => {
    console.log(event.request);
    event.respondWith(
        fetch(event.request).catch(() => caches.match(event.request))
    )
});`

The above displayed is service worker code.
Thanks in advance



Solution

It seems to me that the problem is that you’re caching the files correctly, but when you’re offline and the service worker is trying to fetch the precached assets, you actually request them from the network:

this.addEventListener('fetch', event => {
    console.log(event.request);
    event.respondWith(
        fetch(event.request).catch(() => caches.match(event.request))
    )
});

You should do something like this:

event.respondWith(
    caches.open(cacheName).then((cache) => {
        return cache.match(evt.request).then((response) => {
            // get from the cache, then make a network request if theres no cache
            return response || fetch(event.request);
        } 
    }
)


This Question was asked in StackOverflow by Deeksha Mulgaonkar and Answered by Ray Kim, It is licensed under the terms of
CC BY-SA 2.5.CC BY-SA 3.0.CC BY-SA 4.0.

people found this article helpful. What about you?