Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

offlineFallback from Workbox is not working when going offline

I am trying to implement an offline fallback functionality for pictures and documents that are not available in the cache. The idea is that when the desired pictures or documents are not available, the service worker would serve a predefined fallback picture or document. I am using the recipe described here but it is not working. To test it using the Chrome dev tools I do the following:

  1. go to localhost:3003/ (where the app is served)
  2. let the browser register the service worker
  3. reload the page
  4. go to the Application tab and Service Worker section and select the offline checkbox
  5. reload the page again
  6. get the following error for pictures and documents that are not saved in the cache: GET http://localhost:3003/assets/img/Innomaps%20en%20el%20Hult%20Prize%202019.jpg net::ERR_INTERNET_DISCONNECTED

service worker code:

importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.1/workbox-sw.js');

workbox.core.setCacheNameDetails({
  prefix: 'innomaps-pwa',
  suffix: 'v1',
  precache: 'precache-cache',
  runtime: 'runtime-cache'
});

workbox.precaching.precacheAndRoute([
        // Precaching the home page
        { url: '/', revision: null },
        { url: 'assets/css/styles.css', revision: null },
        { url: 'assets/js/actions.js', revision: null },
        { url: 'assets/img/InnomapsWhite.png', revision: null },
        { url: 'assets/js/bs-init.js', revision: null },
        { url: 'manifest.json', revision: null },

        // Precaching the offline page
        { url: '/offline', revision: null },
]);

workbox.googleAnalytics.initialize();

// This feature is not working!!
workbox.recipes.offlineFallback({
  pageFallback: '/offline',
  imageFallback: 'assets/img/InnomapsWhite.png'
});

the '/' route is serving a simple HTML file.

like image 655
Nico Serrano Avatar asked Dec 01 '25 20:12

Nico Serrano


1 Answers

The problem is that a route handler needs to be setup in order for the offline fallback recipe to catch it. If you are planning to use the offline fallback strategy for all non handled routes (as in my case) you can set up a default handler with your desired strategy (in the following case, the NetworkOnly strategy is used). The following code from @JeffPosnick in his response at my github issue works as a charm:

importScripts('https://storage.googleapis.com/workbox-cdn/releases/6.1.5/workbox-sw.js');

workbox.routing.setDefaultHandler(
  new workbox.strategies.NetworkOnly()
);

// Replace with your URLs.
workbox.recipes.offlineFallback({
  pageFallback: '/offline.html',
  imageFallback: '/offline.png'
});
like image 123
Nico Serrano Avatar answered Dec 04 '25 02:12

Nico Serrano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!