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
});
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;
})
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With