Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i set caches expiration time through javascript using service worker or cache object

I am able to delete cache data using delete method. But i want to automatically delete cache data using expiration time. example it should get deleted in 6 hours.

caches.delete(cacheName).then(function(boolean) {
  // your cache is now deleted
});
like image 530
vishal gupta Avatar asked Oct 23 '25 09:10

vishal gupta


2 Answers

Before sending a cached file to client, You can check when file have been fetch and if it's too old, fetch a new one :

const url = request.url;
caches.open(cacheName).then(cache => {
  cache.match(url).then(response => {
    if(!response) {
      return fetch(url);
    }

    const date = new Date(response.headers.get('date'))
    // if cached file is older than 6 hours
    if(Date.now() > date.getTime() + 1000 * 60 * 60 * 6){
      return fetch(url);
    }

    // else return cached version
    return response;
  })
})
like image 184
ekans Avatar answered Oct 25 '25 00:10

ekans


We don't have an inbuilt method in the cache object to delete the cache after some time but we can use the setTimeout() method which is used to executes a function, once, after waiting a specified number of milliseconds. So, by setting the time you can call this delete method and flush the data.

https://developers.google.com/web/ilt/pwa/caching-files-with-service-worker

The above is the google doc for the cache. Hope this will help you.

like image 26
Gajendran Mohan Avatar answered Oct 25 '25 00:10

Gajendran Mohan