问题
I have a service worker that I want to return an offline page if you're offline. I realized you have to cache the offline page first, so I did that. When I had it cached, and I used chrome dev tools to throttle the network to offline, it showed the default offline page! I don't know how to bring up the page when it is offline. I'm on a chromebook if that would change anything. Here's my code (by the way I am completely new to service workers):
this.addEventListener('install', function(event) {
event.waitUntil(
caches.open('v1').then(function(cache) {
return cache.addAll(['../offline.html','../images/ico/ico.jpg']);
})
);
});
this.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// If fetch fails, we return offline.html from cache.
return fetch(event.request)
.catch(err => {
return caches.match('../offline.html');
});
}
)
);
});
回答1:
Replace your fetch event code with this one. For every request your fetch event will be invoked and it will check if your request is found in the cache file list then it will serve the file from there otherwise it will make the fetch call to get the file from server.
self.addEventListener('fetch', (event) => {
// We only want to call event.respondWith() if this is a navigation request
// for an HTML page.
if (event.request.mode === 'navigate') {
event.respondWith((async () => {
try {
// First, try to use the navigation preload response if it's supported.
const preloadResponse = await event.preloadResponse;
if (preloadResponse) {
return preloadResponse;
}
const networkResponse = await fetch(event.request);
return networkResponse;
} catch (error) {
// catch is only triggered if an exception is thrown, which is likely
// due to a network error.
// If fetch() returns a valid HTTP response with a response code in
// the 4xx or 5xx range, the catch() will NOT be called.
console.log('Fetch failed; returning offline page instead.', error);
const cache = await caches.open(CACHE_NAME);
const cachedResponse = await cache.match(OFFLINE_URL);
return cachedResponse;
}
})());
}
// If our if() condition is false, then this fetch handler won't intercept the
// request. If there are any other fetch handlers registered, they will get a
// chance to call event.respondWith(). If no fetch handlers call
// event.respondWith(), the request will be handled by the browser as if there
// were no service worker involvement.
});
来源:https://stackoverflow.com/questions/64483524/service-worker-not-returning-offline-page-is-returning-default-page