My service-worker.js file won't update automatically when I edit the file then reload the page. however when I debugging on localhost it's work perfectly fine (the service worker update automatically when reload the page just once).
Here is my code service-worker.js
self.addEventListener('install', function(event) {
console.log('[Service Worker] Menginstall Service Worker ...', event);
event.waitUntil(
caches.open(CACHE_STATIC_NAME)
.then(function (cache) {
console.log('[Service Worker] Precaching App Shell');
cache.addAll(CACHE_STATIC_FILES);
})
);
return self.skipWaiting();
});
self.addEventListener('activate', function(event) {
console.log('[Service Worker] Mengaktifkan Service Worker ...', event);
event.waitUntil(
caches.keys()
.then(function (keyList) {
return Promise.all(keyList.map(function (key) {
if(key !== CACHE_STATIC_NAME && key !== CACHE_DYNAMIC) {
console.log('[Service Worker] Removing old cache', key);
return caches.delete(key);
}
}));
})
);
return self.clients.claim();
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function (response) {
if (response) {
return response; //mencari di cache utk ditampilkan
} else {
return fetch(event.request)
.then(function (res) {
return caches.open(CACHE_DYNAMIC)
.then(function (cache) {
cache.put(event.request.url, res.clone());
return res;
});
})
.catch(function (err) {
return caches.open(CACHE_STATIC_NAME)
.then(function (cache) {
return cache.match('offline.html');
});
});
}
})
);
});
And this is the script when I use toast to notify user when update available in the page(something change in the service-worker.js)
function refreshPage() {
var refreshToast = document.querySelector('#snackbar-refresh');
var handler = function() {
window.location.reload();
};
var data = {
message: 'New Update Available',
actionHandler: handler,
actionText: 'Reload',
timeout: 50000
};
refreshToast.MaterialSnackbar.showSnackbar(data);
}
var refreshing;
navigator.serviceWorker.addEventListener('controllerchange',
function() {
if (refreshing) return;
refreshing = true;
refreshPage();
}
);