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?
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.'
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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With