0
votes

I am trying to make my PWA respond with offline.html page when device is offline, and I'm considering failure in fetching homepage as offline but as my service worker caches text/html requests my PWA uses cache to fetch homepage every time.

I am using workbox to generate my PWA, and I have tried removing document from workbox-config.js file.

Code

workbox-config.js

module.exports = {
    globDirectory: 'build/',
    globPatterns: [
        '**/*.{png,ico,css,js}',
    ],
    swDest: 'build\\sw.js',
    swSrc: 'src/sw.js',
    injectionPointRegexp: /(const precacheManifest = )\[\](;)/,
};

Fetch handler in service worker

self.addEventListener('fetch', (event) => {
    console.log('fetch event', event.request.url);
    // request.mode = navigate isn't supported in all browsers
    // so include a check for Accept: text/html header.
    // if (event.request.method === 'GET') {
    //  console.log(event.request.url, event.request.headers.get('accept'));
    // }
    if (event.request.mode === 'navigate' || (event.request.method === 'GET' && event.request.headers.get('accept').includes('text/html'))) {
        event.respondWith(
            fetch(event.request.url).catch((error) => {
                console.log(123, error);
                // Return the offline page
                return caches.match('/offline.html');
            }),
        );
    }
    else {
        event.respondWith(
            caches.match(event.request)
                .then((response) => {
                    if (response) {
                        console.log('Found ', event.request.url, ' in cache');
                        return response;
                    }

                    return fetch(event.request);
                }),
        );
    }
});

I expect that my PWA fetches homepage from my server everytime but instead this is what I'm getting.

current_output

here's the url: https://smartcopy-195fd.firebaseapp.com

1
If you look at the caches section in the application tab, is index.html listed in the cache? - pate
no, it's not there - Nishant Desai
I have added the link to web app. - Nishant Desai

1 Answers

0
votes

Firstly, you need to precache your offline page

workbox.precaching.precacheAndRoute([
  'offline.html'
]);

In order to ensure that your homepage never gets cached, you need to configure it to use a network only strategy:

workbox.routing.registerRoute(
  new RegExp('index.html'),
  new workbox.strategies.NetworkOnly({
      cacheName: 'htmlcache'
    })
); 

Finally, when the fetch fails to find the homepage i.e you are offline, you need to respond from the cache

workbox.routing.setCatchHandler(({event}) => {
      return caches.match(workbox.precaching.getCacheKeyForURL('offline.html'));
});