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

6
我正在尝试使用服务工作者构建离线应用程序。我有一个资源列表,如下所示: var urlsToPrefetch = ['foo.html', 'bar.js'] 许多URL都添加了查询字符串,这导致服务工作者的fetch事件失败,因为请求与缓存中定义的不匹配。查询字符串主要用于强制获取新文件版本。例如,bar.js被请求为bar.js?version=2 虽然Chrome V50尚未实现此选项(ignoreSearch),但有一个忽略查询字符串的选项。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个回答

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

如果你只传入一个URL字符串,Request对象将会被自动创建。请参考https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#cache-matchall-method的5.4.2.3.3章节。此外,由于对于Cache Storage API来说,只有URL是最重要的,所以不必复制所有其他Request属性。 - Jeff Posnick
是的,如果您只需要使用缓存,则最好如此,因为如果“referrer”是跨源URL,则“Request”构造函数可能会抛出异常。 - Marco Castelluccio

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将只给你/


-1

使用Request代替:

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

只有当您想在安装时缓存所有内容时,此方法才有效。 - Marco Castelluccio

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接