2

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

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.