parsley/app/javascript/lib/ServiceWorker.js
2018-04-17 18:38:48 -05:00

49 lines
1.3 KiB
JavaScript

function trackInstall(worker, cb) {
worker.addEventListener('statechange', function() {
//If the worker is now installed, let the user know that there is an update ready
if (worker.state == 'installed') {
cb();
}
});
}
export function swUpdate() {
navigator.serviceWorker.getRegistration().then(reg => {
if (reg && reg.waiting) {
reg.waiting.postMessage("skipWaiting");
window.location.reload(true);
}
});
}
export function swInit(store) {
const updateReady = () => store.commit("setUpdateAvailable", true);
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
.then(function (reg) {
console.log('Registration succeeded. Scope is ' + reg.scope);
if (reg.waiting) {
updateReady();
}
// If there's an updated worker installing, track its progress. If it becomes "installed", call
// indexController._updateReady()
if (reg.installing) {
trackInstall(reg.installing, updateReady);
}
reg.addEventListener('updatefound', function () {
trackInstall(reg.installing, updateReady);
});
}).catch(function (error) {
console.log('Registration failed with ' + error);
});
}
}