Reputation: 88
I'm using vue-pwa for my site and am currently using the NetworkFirst strategy for an API that I call inside my site. I now want to somehow detect if the response I received from the API was cached by the service worker (in which case I want to know how old that cached response is) or if the request was fetched normally. The goal is to display a warning if the user is viewing potentially out of date content (the response was loaded from cache and is older than a few hours)
Here's my current sw.js
self.addEventListener('message', (e) => {
if (!e.data) {
return
}
switch (e.data) {
case 'skipWaiting':
self.skipWaiting()
break
default:
break
}
})
workbox.core.clientsClaim()
self.__precacheManifest = [].concat(self.__precacheManifest || [])
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
workbox.routing.registerRoute(/^https:\/\/some.api.here.com\//, new workbox.strategies.NetworkFirst(), 'GET');
Upvotes: 1
Views: 875
Reputation: 784
First of all it's important to have the correct CORS headers in your API (if it lives on an origin different than the website's). This is necessary in order to get the full response back instead of opaque responses.
Now for getting the time the item was cached, you have to access the Response object from within the Cache.
Each resource cached by Workbox can be found as a key within a Cache as a Response object.
After finding the Response object for the specific resource you are looking for, get the Date HTTP header from the Response:
let cacheNames = await caches.keys()
let cachesStorage = {}
let promises = cacheNames.map(async cacheName => {
const cache = await caches.open(cacheName)
const cachedResources = await cache.keys()
for (const request of cachedResources) {
const response = await cache.match(request)
console.log(response.headers.get('Date'))
// CHECK DATE HERE AND COMPARE WITH CURRENT DATE
}
return cacheName
})
await Promise.all(promises)
Upvotes: 1