Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if URL exist in service worker cache

I have written below code for check if particular URL is already in service worker cache or not ? But Even if the URL is not present in cache, it 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;
        });
      })
}

Calling above function as

cache.isExistInCache('http://localhost:8080/myroom.css').then(function(isExist){
        console.log(isExist);
    })
like image 231
Vivek Pratap Singh Avatar asked Mar 13 '23 08:03

Vivek Pratap Singh


1 Answers

From the documentation of the Cache.match function, the promise is always resolved. It is resolved with a Response object or with undefined if no match is found.

Therefore, you have to modify your function like this:

return caches.open(this.cacheName)
.then(function(cache) {
  return cache.match(request)
  .then(function(response) {
    return !!response; // or `return response ? true : false`, or similar.
  });
});
like image 96
Marco Castelluccio Avatar answered Mar 23 '23 20:03

Marco Castelluccio