Reputation: 2790
I have cached resources with CacheAddall method with a version say "v22" with the v22 version there are many files as for example below:
Now how I can access the same and update or delete individually. I can access the v22 with
caches.keys().then(keys => {
keys.map(key => {
console.log(key)
})
})
but here console.log
only return v22
, how how can access for example /pwa/js/app/js
I couldn't find a workaround for this.
Upvotes: 0
Views: 721
Reputation: 2790
I get this to work, but still looking for a better solution.
self.addEventListener('push', function(event) { console.log("sync event", event); var eventData = event.data.json(); console.log(eventData);
if (eventData.notification.tag === 'notice') {
var token='';
var userId = localforage.getItem("userId");
localforage.getItem("access-token").then(function(value){
token += value;
console.log(token);
console.log(userId);
var request = new Request("https://myurl/api/notice",{
"headers": {
'Authorization' : 'Bearer ' + token,
},
})
fetch(request).then(function(response) {
var rsp = response.clone();
// cache response for the next time around
return caches.open(cacheName).then(function (cache) {
cache.put(request,rsp);
});
});
})
}
});
Upvotes: 0
Reputation: 802
First you need to install callback as per you version name(ex: v22). So, we need to take the following steps:
1)Open a cache. 2)Cache our files. 3)Confirm whether all the required assets are cached or not.
For more clarity you can reach the below urls. https://developers.google.com/web/fundamentals/primers/service-workers
Like below code.
var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = [
'/',
'/styles/main.css',
'/script/main.js'
];
self.addEventListener('install', function(event) {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
Then for access you need to use fetch
event of service worker.
Like below code.
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
For update and delete you can use activate
event of service worker. Please read the cacheWhitelist
properly. But,If you want to update you must be need to change the chachname/version
name of service worker. For delete you can direct delete using map()
.
Like below code.
self.addEventListener('activate', function(event) {
var cacheWhitelist = [cacheName];
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (cacheWhitelist.indexOf(cacheName) === -1) {
return caches.delete(cacheName);
}
})
);
})
);
});
I hope it's help you..!!
Upvotes: 3