0

我有一个使用 workbox 2.0.0 的服务人员,对于某些页面,我使用的是 workboxSW.strategies.staleWhileRevalidate() 缓存策略:

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
);

一切顺利,我可以即时更新从缓存中获得的响应。但我想即时修改所有响应,包括第一次从网络获取它们时(我必须在其中插入一些 javascript)。

从我的测试来看,cachedResponseWillBeUsed 只允许对来自缓存的响应进行后处理(根据方法名称),但我还没有找到一种方法来访问网络响应(否则通常仍然使用 staleWhileRevalidate 策略。)

有什么建议吗?

非常感谢

4

1 回答 1

0

您是正确的,因为没有RequestWrapper与成功返回的网络请求相对应的生命周期事件。(如果您想看到它被添加进来,fetchDidSucceed或者类似的东西,请随时打开一个功能请求!)

您可以通过编写自己的自定义处理程序来解决此问题,该处理程序调用strategies.staleWhileRevalidate然后在返回响应之前对响应执行一些操作,如下所示:

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
);
于 2017-09-07T14:59:52.260 回答