2
votes

I'm using workbox-webpack-plugin to register service worker. My frontend app is react-redux app configured with webpack. If you visit app url, you can always see login view.

My plugin inside webpack.config.js:

new InjectManifest({
  swSrc: path.join('src', 'service-worker.js')
})

Service worker:

workbox.skipWaiting();
workbox.clientsClaim();

workbox.precaching.precacheAndRoute(self.__precacheManifest);

My service worker caches all my splitted routes. But that doesn't matter - even if they all are cached, when user without connection visits my app, he cannot login. That's why I need a way to check if user is in offline mode, and instead of returning login, return 'offline.html' page.

I found out that my env.config.js file (which contains API URLS and is requested on login page) is not cached, so I think it would be easy to catch error while not getting this file. So I added following in my service worker:

workbox.routing.registerRoute(
  new RegExp('/env.config.js'),
  ({event}) => {
    return networkFirstHandler.handle({event})
      .catch(() => caches.match('/offline.html'));
  }
);

But it doesn't return offline.html in browser. It seems like 'offline.html' file is returned instead of 'env.config.js' file.

How to accomplish this? I'm new to workbox plugin and it would be great to see some suggestions.

1

1 Answers

0
votes
importScripts("/precache-manifest.81b400bbc7dc89de30f4854961b64d1d.js", "https://storage.googleapis.com/workbox-cdn/releases/3.4.1/workbox-sw.js");

workbox.skipWaiting();
workbox.clientsClaim();

const STATIC_FILES = [
  '/env.config.js',
];


self.__precacheManifest = STATIC_FILES.concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest);

Update - since I decided to cache env.config.js file I'm only getting API error while using app offline. Maybe this API call (which returns error because of no connection) is a good trigger to display offline page? I think it is, but I still don't know.

When I try something like this:

workbox.routing.registerRoute(
  new RegExp(API_REGEX_GOES_HERE),
  ({event}) => {
    return networkFirstHandler.handle({event})
      .catch(() => caches.match('/offline.html'));
  }
);

The "offline.html" page will be returned instead of API request. So it will not be displayed like a page...