有没有办法使用工作箱从下面注册的路线中忽略查询字符串“?screenSize =”!如果我可以使用正则表达式,我将如何在下面的场景中编写它?基本上,无论screenSize查询字符串是什么,我都希望匹配缓存。
workboxSW.router.registerRoute('https://example.com/data/image?screenSize=980',
workboxSW.strategies.cacheFirst({
cacheName: 'mycache',
cacheExpiration: {
maxEntries: 50
},
cacheableResponse: {statuses: [0, 200]}
})
);
答案 0 :(得分:4)
更新:从Workbox v4.2.0开始,新的cacheKeyWillBeUsed
生命周期回调可以帮助覆盖读取和写入操作的默认缓存键:https://github.com/GoogleChrome/workbox/releases/tag/v4.2.0
原始回复:
您应该可以通过编写在配置策略时传入的cachedResponseWillBeUsed
plugin来执行此操作:
// See https://workboxjs.org/reference-docs/latest/module-workbox-runtime-caching.RequestWrapper.html#.cachedResponseWillBeUsed
const cachedResponseWillBeUsed = ({cache, request, cachedResponse}) => {
// If there's already a match against the request URL, return it.
if (cachedResponse) {
return cachedResponse;
}
// Otherwise, return a match for a specific URL:
const urlToMatch = 'https://example.com/data/generic/image.jpg';
return caches.match(urlToMatch);
};
const imageCachingStrategy = workboxSW.strategies.cacheFirst({
cacheName: 'mycache',
cacheExpiration: {
maxEntries: 50
},
cacheableResponse: {statuses: [0, 200]},
plugins: [{cachedResponseWillBeUsed}]
});
workboxSW.router.registerRoute(
new RegExp('^https://example\.com/data/'),
imageCachingStrategy
);
答案 1 :(得分:1)
从v5开始,基于aw04的答案,代码应如下所示:
const ignoreQueryStringPlugin = {
cachedResponseWillBeUsed: async({cacheName, request, matchOptions, cachedResponse, event}) => {
console.log(request.url);
if (cachedResponse) {
return cachedResponse;
}
// this will match same url/diff query string where the original failed
return caches.match(request.url, {ignoreSearch: true});
}
};
registerRoute(
new RegExp('...'),
new NetworkFirst({
cacheName: 'cache',
plugins: [
ignoreQueryStringPlugin
],
})
);
答案 2 :(得分:0)
要以other答案为基础,caches.match有一个选项ignoreSearch
,因此我们可以使用相同的网址重试:
cachedResponseWillBeUsed = ({cache, request, cachedResponse}) => {
if (cachedResponse) {
return cachedResponse;
}
// this will match same url/diff query string where the original failed
return caches.match(request.url, { ignoreSearch: true });
};
答案 3 :(得分:0)
ignoreURLParametersMatching
参数对我有用:
https://developers.google.com/web/tools/workbox/modules/workbox-precaching#ignore_url_parameters
答案 4 :(得分:0)
您可以简单地使用 cacheKeyWillBeUsed
,修改保存的缓存键以完全忽略查询,并匹配对任何查询的 url 的每个响应。
const ignoreQueryStringPlugin = {
cacheKeyWillBeUsed: async ({request, mode, params, event, state}) => {
//here you can extract the fix part of the url you want to cache without the query
curl = new URL(request.url);
return curl.pathname;
}
};
并将其添加到策略中
workbox.routing.registerRoute(/\/(\?.+)?/,new
workbox.strategies.StaleWhileRevalidate({
matchOptions: {
ignoreSearch: true,
},
plugins: [
ignoreQueryStringPlugin
],
}));