问题
For having the "add tome homescreen" alert displayed, I want to integrate a service-worker and an offline capability of the application: When the user is offline, the app should simply display a special offline HTML file.
My service-worker looks like this:
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.1.0/workbox-sw.js');
const CACHE_VERSION = 1;
workbox.core.setCacheNameDetails({
prefix: 'app',
suffix: 'v' + CACHE_VERSION
});
workbox.routing.registerRoute(
'/offline-page.html',
workbox.strategies.networkFirst({
networkTimeoutSeconds: 2,
cacheableResponse: { statuses: [0, 200] },
})
)
workbox.routing.registerRoute(
({ event }) => event.request.mode === 'navigate',
({ url }) =>
fetch(url.href, { credentials: 'include', redirect: 'follow', }).catch(() => caches.match('/offline-page.html'))
)
But as soon as my application returns a 302 redirect (e.g. after login oder logout), I get the following warning message in the console:
The FetchEvent for "https://app.com" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow".
and Google Chrome diplays an error page (ERR_FAILED) saying that the website can't be reached.
Does anyone have an idea how to fix this?
回答1:
You can adapt the "Provide a fallback response to a route" recipe in the docs to accommodate your particular restrictions.
There are a couple of different options for accomplishing this, but the cleanest would be to create your own network-only strategy (to mimic the fetch()
that you're using in your example), chain .catch()
to the end of it, and then use that as the handler
when constructing a NavigationRoute.
That will give you a Route
that you could then pass to workbox.routing.registerRoute().
// You're responsible for either precaching or
// explicitly adding OFFLINE_HTML to one of the caches.
const OFFLINE_HTML = '/offline-page.html';
const networkOnly = workbox.strategies.networkOnly();
const networkOnlyWithFallback = networkOnly().catch(() => caches.match(OFFLINE_HTML));
const route = new workbox.routing.NavigationRoute(networkOnlyWithFallback);
workbox.routing.registerRoute(route);
回答2:
This seems to do the trick:
const FALLBACK_URL = '/';
const networkOnly = workbox.strategies.networkOnly();
const route = new workbox.routing.NavigationRoute(({event}) => {
return networkOnly.handle({event})
.catch(() => caches.match(FALLBACK_URL));
});
workbox.routing.registerRoute(route);
来源:https://stackoverflow.com/questions/50074107/302-redirects-do-not-work-in-a-service-worker-built-with-google-workbox