使用工作箱时如何从缓存的 url 中忽略 url 查询字符串?

seU*_*ser 1 caching fetch service-worker progressive-web-apps workbox

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

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

尝试 cachedResponseWillBeUsed 插件后:我没有看到应用了该插件: 在此处输入图片说明

Jef*_*ick 5

更新:从 Workbox v4.2.0 开始,新的cacheKeyWillBeUsed生命周期回调可以帮助覆盖读取和写入操作的默认缓存键:https : //github.com/GoogleChrome/workbox/releases/tag/v4.2.0

原回复:

您应该能够通过编写在配置策略时传入的cachedResponseWillBeUsed插件来做到这一点:

// 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
);
Run Code Online (Sandbox Code Playgroud)