忽略服务工作者请求中的查询参数

时间:2016-03-05 03:33:55

标签: javascript service-worker

我正在尝试使用服务工作者构建一个离线应用。我有一个资源列表,如

var urlsToPrefetch = ['foo.html', 'bar.js']

查询字符串被添加到许多网址中,这导致服务工作者的fetch事件失败,因为请求与缓存中定义的内容不匹配。查询字符串主要用于强制获取新文件版本。例如,bar.js

请求bar.js?version=2

有一个忽略查询字符串的选项(下面是ignoreSearch),尽管从Chrome V50开始尚未实现。 Chrome Canary仅适用于Win / Mac

以下代码位于fetch eventListener

event.respondWith(
    // caches.match() will look for a cache entry in all of the caches available to the service worker.
    // It's an alternative to first opening a specific named cache and then matching on that.

    caches.match(event.request, {'ignoreSearch': true} ).then(function(response) {
        if (response) {

            return response;
        }

        ...
)

3 个答案:

答案 0 :(得分:3)

您可以创建一个删除查询字符串的新请求,然后使用它而不是原始查询字符串:

var url = new URL(request.url);
url.search = '';
url.fragment = '';

let cleanRequest = new Request(url, {
  method: request.method,
  headers: request.headers,
  mode: request.mode,
  credentials: request.credentials,
  cache: request.cache,
  redirect: request.redirect,
  referrer: request.referrer,
  integrity: request.integrity,
});

答案 1 :(得分:0)

尝试...

function stripQueryStringAndHashFromPath(url) {
  return url.split("?")[0].split("#")[0];
}

function onFetch(event) {
  const requestUrl = stripQueryStringAndHashFromPath(event.request.url.replace(/^.*\/\/[^\/]+/, ''));
... all the other jazz
}

这将只为您提供路径名。例如,/?test=1#three只会给您/

答案 2 :(得分:-1)

改为使用Request

var requestsToCache = [
  new Request('foo.html'),
  new Request('bar.js')
];
// ...
  cache.addAll(requestsToCache);
// ...