Prevent fetch response and cache update if response is redirected

This commit is contained in:
schlagmichdoch 2025-02-24 20:17:54 +01:00
parent 148eb79ef0
commit d7b68e214e

View file

@ -1,6 +1,5 @@
const cacheVersion = 'v1.11.1'; const cacheVersion = 'v1.11.1';
const cacheTitle = `pairdrop-cache-${cacheVersion}`; const cacheTitle = `pairdrop-cache-${cacheVersion}`;
const forceFetch = false; // FOR DEVELOPMENT: Set to true to always update assets instead of using cached versions
const relativePathsToCache = [ const relativePathsToCache = [
'./', './',
'index.html', 'index.html',
@ -76,20 +75,25 @@ self.addEventListener('install', function(event) {
const fromNetwork = (request, timeout) => const fromNetwork = (request, timeout) =>
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
const timeoutId = setTimeout(reject, timeout); const timeoutId = setTimeout(reject, timeout);
fetch(request) fetch(request, {cache: "no-store"})
.then(response => { .then(response => {
if (response.redirected) {
throw new Error("Fetch is redirect. Abort usage and cache!");
}
clearTimeout(timeoutId); clearTimeout(timeoutId);
resolve(response); resolve(response);
// Prevent requests that are in relativePathsNotToCache from being cached
if (doNotCacheRequest(request)) return; if (doNotCacheRequest(request)) return;
update(request) updateCache(request)
.then(() => console.log("Cache successfully updated for", request.url)) .then(() => console.log("Cache successfully updated for", request.url))
.catch(reason => console.log("Cache could not be updated for", request.url, "Reason:", reason)); .catch(err => console.log("Cache could not be updated for", request.url, err));
}) })
.catch(error => { .catch(error => {
// Handle any errors that occurred during the fetch // Handle any errors that occurred during the fetch
console.error(`Could not fetch ${request.url}. Are you online?`); console.error(`Could not fetch ${request.url}.`);
reject(error); reject(error);
}); });
}); });
@ -111,16 +115,16 @@ const doNotCacheRequest = request => {
}; };
// cache the current page to make it available for offline // cache the current page to make it available for offline
const update = request => new Promise((resolve, reject) => { const updateCache = request => new Promise((resolve, reject) => {
if (doNotCacheRequest(request)) {
reject("Url is specifically prevented from being cached in the serviceworker.");
return;
}
caches caches
.open(cacheTitle) .open(cacheTitle)
.then(cache => .then(cache =>
fetch(request, {cache: "no-store"}) fetch(request, {cache: "no-store"})
.then(response => { .then(response => {
if (response.redirected) {
throw new Error("Fetch is redirect. Abort usage and cache!");
}
cache cache
.put(request, response) .put(request, response)
.then(() => resolve()); .then(() => resolve());
@ -129,9 +133,10 @@ const update = request => new Promise((resolve, reject) => {
); );
}); });
// general strategy when making a request (eg if online try to fetch it // general strategy when making a request:
// from cache, if something fails fetch from network. Update cache everytime files are fetched. // 1. Try to retrieve file from cache
// This way files should only be fetched if cacheVersion is changed // 2. If cache is not available: Fetch from network and update cache.
// This way, cached files are only updated if the cacheVersion is changed
self.addEventListener('fetch', function(event) { self.addEventListener('fetch', function(event) {
if (event.request.method === "POST") { if (event.request.method === "POST") {
// Requests related to Web Share Target. // Requests related to Web Share Target.
@ -141,39 +146,46 @@ self.addEventListener('fetch', function(event) {
})()); })());
} }
else { else {
// Regular requests not related to Web Share Target. // Regular requests not related to Web Share Target:
if (forceFetch) { // If request is excluded from cache -> respondWith fromNetwork
event.respondWith(fromNetwork(event.request, 10000)); // else -> try fromCache first
} event.respondWith(
else { doNotCacheRequest(event.request)
event.respondWith( ? fromNetwork(event.request, 10000)
fromCache(event.request) : fromCache(event.request)
.then(rsp => { .then(rsp => {
// if fromCache resolves to undefined fetch from network instead // if fromCache resolves to undefined fetch from network instead
return rsp || fromNetwork(event.request, 10000); if (!rsp) {
throw new Error("No match found.");
}
return rsp;
}) })
); .catch(error => {
} console.error("Could not retrieve request from cache:", event.request.url, error);
return fromNetwork(event.request, 10000);
})
);
} }
}); });
// on activation, we clean up the previously registered service workers // on activation, we clean up the previously registered service workers
self.addEventListener('activate', evt => { self.addEventListener('activate', evt => {
return evt.waitUntil( return evt.waitUntil(
caches.keys() caches
.then(cacheNames => { .keys()
return Promise.all( .then(cacheNames => {
cacheNames.map(cacheName => { return Promise.all(
if (cacheName !== cacheTitle) { cacheNames.map(cacheName => {
return caches.delete(cacheName); if (cacheName !== cacheTitle) {
} console.log("Delete cache:", cacheName);
}) return caches.delete(cacheName);
); }
}) })
) );
} })
); )
});
const evaluateRequestData = function (request) { const evaluateRequestData = function (request) {
return new Promise(async (resolve) => { return new Promise(async (resolve) => {