I have a service worker using workbox 2.0.0, and for some pages, I am using the workboxSW.strategies.staleWhileRevalidate() caching strategy:
const customFilter = {
cachedResponseWillBeUsed: function (input) {
try {
console.log('cacheResponseWillBeUsed for : ' + input.request.url);
// modify the response body here
} catch (e) {
console.error(e);
}
return input.cachedResponse;
},
requestWillFetch: function (input) {
try {
console.log('requestWillFetch for ' + input.request.url);
} catch (e) {
console.error(e);
}
return input.request;
},
fetchDidFail: function (input) {
console.log('A fetch request for ' + input.request.url + ' failed.');
}
}
const cachingStrategy = workboxSW.strategies.staleWhileRevalidate({
plugins: [
customFilter
]
});
workboxSW.router.registerRoute(
new RegExp('\/(.*)/suffix/?$'),
cachingStrategy
);
That goes well, and I can update on the fly responses obtained from the cache. But I would like to modify on the fly ALL responses, including when they are obtained from the network the first time (I have to insert some javascript in them).
From my testing, cachedResponseWillBeUsed only allows to postprocess response from the cache (as per the method name), but I have not found a way yet to get access to networked responses (while still using the staleWhileRevalidate strategy normally otherwise.)
Any advice?
Many thanks
You're correct in that there's no
RequestWrapper
lifecycle event that corresponds to a network request being successfully returned. (If you'd like to see it added in, asfetchDidSucceed
or something similar, feel free to open a feature request!)You could work around this by writing your own custom handler that called
strategies.staleWhileRevalidate
and then did something with the response before returning it, like so: