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

Javascript 忽略服务工作者请求中的查询参数,javascript,service-worker,Javascript,Service Worker,我正在尝试使用服务人员构建一个离线应用程序。我有一个资源列表,定义如下 var urlsToPrefetch=['foo.html','bar.js'] 查询字符串被添加到许多URL中,这导致服务工作人员的fetch事件失败,因为请求与缓存中定义的内容不匹配。查询字符串主要用于强制获取新文件版本。例如,bar.js被请求为bar.js?version=2 有一个忽略查询字符串的选项(ignoreSearch),尽管这在Chrome V50中还没有实现。Chrome Canary仅适用于Win/M

我正在尝试使用服务人员构建一个离线应用程序。我有一个资源列表,定义如下

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

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

有一个忽略查询字符串的选项(
ignoreSearch
),尽管这在Chrome V50中还没有实现。Chrome Canary仅适用于Win/Mac

以下代码位于
fetcheventlistener

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

        ...
)

改用
请求

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

您可以创建一个新的请求,删除查询字符串,然后使用它来代替原来的查询字符串:

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,
});
试试看


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

这仅在您希望缓存安装时的所有内容时有效。如果您只需传入URL字符串,将自动创建
请求。参见第5.4.2.3.3节,也没有必要复制所有其他
请求
属性,因为只有URL对缓存存储API很重要。是的,如果您只需要使用缓存,实际上会更好,因为
请求
构造函数可以在
引用者
是跨源URL时抛出。
function stripQueryStringAndHashFromPath(url) {
  return url.split("?")[0].split("#")[0];
}

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