如何在使用工作箱时忽略来自缓存URL的url查询字符串?

问题描述 投票:0回答:3

有没有办法使用工作箱从下面注册的路线中忽略查询字符串“?screenSize =”!如果我可以使用正则表达式,我将如何在下面的场景中编写它?基本上,无论screenSize查询字符串是什么,我都希望匹配缓存。

workboxSW.router.registerRoute('https://example.com/data/image?screenSize=980',
workboxSW.strategies.cacheFirst({
    cacheName: 'mycache',
    cacheExpiration: {
        maxEntries: 50
    },
    cacheableResponse: {statuses: [0, 200]}
})
);

尝试cachedResponseWillBeUsed插件后:我没有看到插件被应用:enter image description here

caching fetch service-worker progressive-web-apps workbox
3个回答
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
);

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

© www.soinside.com 2019 - 2024. All rights reserved.