后处理网页内容与staleWhileRevalidate
问题描述:
我用针线2.0.0服务工作者,以及一些网页,我现在用的是workboxSW.strategies.staleWhileRevalidate()的缓存策略:后处理网页内容与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策略)。
有什么建议吗?
非常感谢
答
你在正确的没有对应于网络请求被成功返回RequestWrapper
生命周期事件。 (如果你想看到它加了进来,作为fetchDidSucceed
或类似的东西,随意打开一个feature request!)
您可以解决此通过编写一个名为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
);
这正是我最终做的(尽管花了一点时间才弄清楚)。 – Weeblr
对不起,快速输入。事实证明,使用cachedResponseWillBeUsed来修改响应并不是一个好主意。如果这样做,则不能再使用WorkBox的cacheExpiration选项,因为只能注册一个cachedResponseWillBeUsed方法。如此专门的方法来过滤响应确实是一个好主意。 – Weeblr