11
votes

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

2
What is the expected outcome? - noogui
@noogui the outcome should be like, the files should be cached in offline mode too. As i already said, it is getting cached in online mode, but as soon as i shift to offline mode, the cache storage becomes empty. The expected outcome should be, the cached files will be displayed when I am in offline mode or when network is not available. - Deeksha Mulgaonkar
Sounds to me like a Chrome bug. You should file an issue with them. - abraham
I don't see that behavior in Chrome. Did your site pass a Lighthouse audit? - TimHayes
Seeing the same behaviour in chrome version 70.0.3538.110 - Ally

2 Answers

0
votes

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

Issue

I was facing similar issue while working on the service worker. The moment I marked the network as offline, the cache used to disappear from the Cache Storage. The issue this happened is because I had kept my service worker file inside the javascripts folder. Just like OP has placed inside a service-worker folder. Now the above leads to the scope issue.


Fix

Hence, in-order to make your service worker work (no pun intended), you need to move your service worker file to the root dir (emphasis on security while you do so).


Documentation

As MDN quotes:

The service worker will only catch requests from clients under the service worker's scope.

The max scope for a service worker is the location of the worker.

You can also set a scope by passing the scope path while registering your Service Worker like

navigator.serviceWorker
  .register('/cache-worker.js', {
    scope: '/some-folder' 
    /* but again, you can never put your service worker inside a dir and 
       try to set a scope which is outside of the service worker dir. 
       It can always be at a lower level than where your service worker file resides..
  })

...