检查 Service Worker 缓存中是否存在 URL

Check if URL exist in service worker cache

我写了下面的代码来检查特定的 URL 是否已经在 service worker 缓存中?但是即使缓存中不存在 URL,它也会 returns/consoles "Found in cache"。

var isExistInCache = function(request){
    return caches.open(this.cacheName).then(function(cache) {
        return cache.match(request).then(function(response){
            debug_("Found in cache "+response,debug);
            return true;
        },function(err){
            debug_("Not found in cache "+response,debug);
            return false;
        });
      })
}

调用上面的函数作为

cache.isExistInCache('http://localhost:8080/myroom.css').then(function(isExist){
        console.log(isExist);
    })

来自 Cache.match function, the promise is always resolved. It is resolved with a Response 对象的文档,如果未找到匹配项,则使用 undefined。

因此,您必须像这样修改函数:

return caches.open(this.cacheName)
.then(function(cache) {
  return cache.match(request)
  .then(function(response) {
    return !!response; // or `return response ? true : false`, or similar.
  });
});