Skip to content

Instantly share code, notes, and snippets.

@zwacky
Last active October 19, 2020 11:12
Show Gist options
  • Save zwacky/cb571712da759f1fd64a5951396f1f7c to your computer and use it in GitHub Desktop.
Save zwacky/cb571712da759f1fd64a5951396f1f7c to your computer and use it in GitHub Desktop.
registers a service-worker which is wrapped in a promise that resolves with the value whether the service-worker has been updated or not
// make the whole serviceworker process into a promise so later on we can
// listen to it and in case new content is available a toast will be shown
window.isUpdateAvailable = new Promise(function(resolve, reject) {
// lazy way of disabling service workers while developing
if ('serviceWorker' in navigator && ['localhost', '127'].indexOf(location.hostname) === -1) {
// register service worker file
navigator.serviceWorker.register('service-worker.js')
.then(reg => {
reg.onupdatefound = () => {
const installingWorker = reg.installing;
installingWorker.onstatechange = () => {
switch (installingWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
// new update available
resolve(true);
} else {
// no update available
resolve(false);
}
break;
}
};
};
})
.catch(err => console.error('[SW ERROR]', err));
}
});
// Update:
// this also can be incorporated right into e.g. your run() function in angular,
// to avoid using the global namespace for such a thing.
// because the registering of a service worker doesn't need to be executed on the first load of the page.
@ZachMoreno
Copy link

Thanks kindly for this solution, I found it on Medium. After the first update is triggered, subsequent service worker builds leave the promise in pending state, causing the toast to fail. Any thoughts?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment