I am trying to set up my site service worker to display an offline.html file when offline instead of whichever HTML file the user was trying to fetch that was not in the cache.
Following the Workbox docs (https://developers.google.com/web/tools/workbox/guides/advanced-recipes#provide_a_fallback_response_to_a_route), I wrote the code below, but whenever I tick the offline checkbox in Chrome DevTools and visit an HTML page to test it, I get Chrome's standard "No internet" dinosaur page.
workbox.precaching.precacheAndRoute([
'/offline.html'
]);
workbox.routing.setCatchHandler(({ event }) => {
switch (event.request.destination) {
case 'document':
return caches.match(workbox.precaching.getCacheKeyForURL('/offline.html'));
break;
default:
return Response.error();
}
});
You forgot to register a route. Hence the workbox.routing.setCatchHandler function is never invoked.
Adding this code to your Service Worker should solve the issue
workbox.routing.registerRoute(
new RegExp('.html'),
new workbox.strategies.NetworkOnly({
cacheName: 'htmlcache'
})
);
You can also refer to this example: https://progressify.org/building-a-pwa-with-an-offline-fallback-page-using-workbox/