Search code examples
javascriptcachingresponse-headers

Access cache response headers with JavaScript


I am trying to access the response header "date" from one of my cached elements.

As you can see in the picture, my request does not return the correct timestamp. Instead, it returns null, and I don't know why.

enter image description here

Here is the code I use:

var cachedFile = "https://www.washingtonpost.com/resizer/rgjyoeu2BaoUyNiojHCKLjN9udM=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/EXKAUXTXXUI6TJ57ZCSDXBHOGE.jpg";
caches.open("dynamic-content").then(cache => {
  cache.match(cachedFile).then(response => {
    if(! response){
        console.log("not found");
    }else{
        var element = response.headers.get('date');
        console.log(element);
    }
  })
})

My goal is to delete old cached files. Without using workbox or any plugins. If someone knows a way, I'm happy to be enlightened ;)


Solution

  • try (your request return empty headers)

    let cache={};
    
    var url = "https://cors-anywhere.herokuapp.com/https://www.washingtonpost.com/resizer/rgjyoeu2BaoUyNiojHCKLjN9udM=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/EXKAUXTXXUI6TJ57ZCSDXBHOGE.jpg";
    
    async function load(url) {
      let c = cache[url];
      if(c) {
        console.log('Cached headers',c.res.headers);
      } else {
        let res = await fetch(url);
        c = cache[url] = {
          res,
          pic: await res.blob(),
        }
      }
      image.src=""; 
      image.src = URL.createObjectURL(c.pic);
    }
    
    function start() {
      load(url);
      btn.innerText="Load from cache";
      
    }
    <button id="btn" onclick="start()">Load</button><br>
    <img id="image" height="150"/>