Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workbox - SPA - fallback to /index.html

I'm using workbox with webpack to generate a service worker.

With the following code in webpack.config.js:

new WorkboxPlugin.InjectManifest({
  swSrc: "./src/sw.js"
}),

a service worker is generated nicely.

In ./src/sw.js, I have:

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

And all of my assets are precached nicely.

However, I have a single page application and I noticed that when refreshing the page while offline from a non-homepage route, the service worker doesn't respond. For example, when refreshing /page1 while offline doesn't work, but refreshing / does work.

How can I configure workbox to use a runtime strategy that uses /index.html as a fallback for HTML requests?

Note

Doing something like this:

new WorkboxPlugin.InjectManifest({
  swSrc: "./src/sw.js",
  navigationFallback: "/index.html"
})

does not work since navigationFallback is not a valid option in it's above usage.

{ message: '"navigationFallback" is not a supported parameter.'
like image 732
Raphael Rafatpanah Avatar asked May 26 '18 02:05

Raphael Rafatpanah


2 Answers

Luckily, workbox has made this an easy solve.

If your site is a single page app, you can use a NavigationRoute to return a specific response for all navigation requests.

workbox.routing.registerNavigationRoute('/single-page-app.html');

In my case:

workbox.routing.registerNavigationRoute('/index.html');

Source: https://developers.google.com/web/tools/workbox/modules/workbox-routing#how_to_register_a_navigation_route

like image 94
Raphael Rafatpanah Avatar answered Sep 23 '22 07:09

Raphael Rafatpanah


For workbox v4 or below, use workbox.routing.registerNavigationRoute (see another answer).

The recipe is changed in v5:

import {precacheAndRoute, createHandlerBoundToURL} from 'workbox-precaching'
import {NavigationRoute, registerRoute} from 'workbox-routing'


precacheAndRoute(self.__WB_MANIFEST)
registerRoute(new NavigationRoute(createHandlerBoundToURL('/index.html')))

Note: self.__WB_MANIFEST (renamed from self.__precacheManifest) is provided by WorkboxPlugin.InjectManifest.

like image 21
DarkKnight Avatar answered Sep 21 '22 07:09

DarkKnight