Last active
September 3, 2018 22:39
-
-
Save daliborgogic/dbdeb1eeabb30c391046ed037f9c97f4 to your computer and use it in GitHub Desktop.
Notify when caching is complete or new or updated content is available
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script> | |
mounted () { | |
window.addEventListener('online', () => | |
store.dispatch('snackbar', { id: 0, show: false }) | |
) | |
window.addEventListener('offline', () => | |
store.dispatch('snackbar', { id: 0, show: true }) | |
) | |
window.addEventListener('load', () => { | |
store.dispatch('snackbar', { | |
id: 0, | |
show: navigator.onLine ? false : navigator.onLine | |
}) | |
const isLocalhost = Boolean( | |
window.location.hostname === 'localhost' || | |
// [::1] is the IPv6 localhost address. | |
window.location.hostname === '[::1]' || | |
// 127.0.0.1/8 is considered localhost for IPv4. | |
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/) | |
) | |
if ('serviceWorker' in navigator && (window.location.protocol === 'https:' || isLocalhost)) { | |
navigator.serviceWorker.register('service-worker.js').then(reg => { | |
reg.onupdatefound = () => { | |
const installingWorker = reg.installing | |
installingWorker.onstatechange = () => { | |
switch (installingWorker.state) { | |
case 'installed': | |
store.dispatch('snackbar', { | |
// id: 1 New or updated content is available | |
// id: 2 Caching complete. Future visits will work offline | |
id: navigator.serviceWorker.controller !== null ? 2 : 1, | |
show: true | |
}) | |
break | |
case 'redundant': | |
console.error('The installing service worker became redundant.') | |
break | |
default: | |
// Ignore | |
} | |
} | |
} | |
}).catch(e => { | |
console.error(`Error during service worker registration: ${e}`) | |
}) | |
} | |
}) | |
} | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment