|
| 1 | +<script lang="ts"> |
| 2 | +import { Component, Vue } from 'vue-property-decorator' |
| 3 | +
|
| 4 | +@Component({ |
| 5 | + name: 'ServiceWorkerUpdatePopup' |
| 6 | +}) |
| 7 | +export default class extends Vue { |
| 8 | + private refreshing = false |
| 9 | + private notificationText = 'New content is available!' |
| 10 | + private refreshButtonText = 'Refresh' |
| 11 | + private registration: ServiceWorkerRegistration | null = null |
| 12 | +
|
| 13 | + created() { |
| 14 | + // Listen for swUpdated event and display refresh notification as required. |
| 15 | + document.addEventListener('swUpdated', this.showRefreshUI, { once: true }) |
| 16 | + // Refresh all open app tabs when a new service worker is installed. |
| 17 | + navigator.serviceWorker.addEventListener('controllerchange', () => { |
| 18 | + if (this.refreshing) return |
| 19 | + this.refreshing = true |
| 20 | + window.location.reload() |
| 21 | + }) |
| 22 | + } |
| 23 | +
|
| 24 | + render() { |
| 25 | + // Avoid warning for missing template |
| 26 | + } |
| 27 | +
|
| 28 | + private showRefreshUI(e: Event) { |
| 29 | + // Display a notification inviting the user to refresh/reload the app due |
| 30 | + // to an app update being available. |
| 31 | + // The new service worker is installed, but not yet active. |
| 32 | + // Store the ServiceWorkerRegistration instance for later use. |
| 33 | + const h = this.$createElement |
| 34 | + this.registration = (e as CustomEvent).detail |
| 35 | + this.$notify.info({ |
| 36 | + title: 'Update available', |
| 37 | + message: h('div', { class: 'sw-update-popup' }, [ |
| 38 | + this.notificationText, |
| 39 | + h('br'), |
| 40 | + h('button', { |
| 41 | + on: { |
| 42 | + click: (e: Event) => { |
| 43 | + e.preventDefault() |
| 44 | + this.refreshApp() |
| 45 | + } |
| 46 | + } |
| 47 | + }, this.refreshButtonText) |
| 48 | + ]), |
| 49 | + position: 'bottom-right', |
| 50 | + duration: 0 |
| 51 | + }) |
| 52 | + } |
| 53 | +
|
| 54 | + private refreshApp() { |
| 55 | + // Protect against missing registration.waiting. |
| 56 | + if (!this.registration || !this.registration.waiting) return |
| 57 | + this.registration.waiting.postMessage('skipWaiting') |
| 58 | + } |
| 59 | +} |
| 60 | +</script> |
| 61 | + |
| 62 | +<style lang="scss" scoped> |
| 63 | +.sw-update-popup > button { |
| 64 | + margin-top: 0.5em; |
| 65 | + padding: 0.25em 1.5em; |
| 66 | +} |
| 67 | +</style> |
0 commit comments