简体   繁体   English

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

[英]How to ignore url querystring from cached urls when using workbox?

Is there a way to ignore query string "?screenSize=" from below registered route using workbox!有没有办法使用工作箱从下面的注册路由中忽略查询字符串“?screenSize=”! If I can use regex how would i write it in below scenario?如果我可以使用正则表达式,我将如何在下面的场景中编写它? Basically, I am looking to match the cache no matter what is the screenSize querystring.基本上,无论 screenSize 查询字符串是什么,我都希望匹配缓存。

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

After trying the cachedResponseWillBeUsed plugin: I do not see the plugin is applied:尝试 cachedResponseWillBeUsed 插件后:我没有看到应用了该插件: 在此处输入图片说明

Update: As of Workbox v4.2.0, the new cacheKeyWillBeUsed lifecycle callback can help override the default cache key for both read and write operations: https://github.com/GoogleChrome/workbox/releases/tag/v4.2.0更新:从 Workbox v4.2.0 开始,新的cacheKeyWillBeUsed生命周期回调可以帮助覆盖读取和写入操作的默认缓存键: https : //github.com/GoogleChrome/workbox/releases/tag/v4.2.0

Original response:原回复:

You should be able to do this by writing a cachedResponseWillBeUsed plugin that you pass in when you configure the strategy:您应该能够通过编写在配置策略时传入的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
);

To build on the other answer, caches.match has an option ignoreSearch , so we can simply try again with the same url:为了建立在另一个答案的基础上, caches.match有一个选项ignoreSearch ,所以我们可以简单地使用相同的 url 重试:

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

As of v5, building on aw04's answer, the code should read as follows:从 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
        ],
    })
);

You can use the cacheKeyWillBeUsed simply, modifying the saved cache key to ignore the query at all, and matching for every response to the url with any query.您可以简单地使用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;

 }
};

and add it to the strategy并将其添加到策略中

workbox.routing.registerRoute(/\/(\?.+)?/,new 
 workbox.strategies.StaleWhileRevalidate({
  matchOptions: {
   ignoreSearch: true,
  },
  plugins: [
   ignoreQueryStringPlugin
  ],
}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM