Postprocess page content with staleWhileRevalidate

306 views Asked by At

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

1

There are 1 answers

2
Jeff Posnick On

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, as fetchDidSucceed 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:

const staleWhileRevalidate = workboxSW.strategies.staleWhileRevalidate({
  plugins: [...],
});

const cachingStrategy = async (params) => {
  const response = await staleWhileRevalidate(params);
  // Do something to response, like get its body, modify it,
  // and create a new response with the updated body.
  const modifiedResponse = modify(response);
  return modifiedResponse;
};

workboxSW.router.registerRoute(
    new RegExp('\/(.*)/suffix/?$'),
    cachingStrategy
);