Inform App.vue a Service-Worker Event is Being Called Inform App.vue a Service-Worker Event is Being Called vue.js vue.js

Inform App.vue a Service-Worker Event is Being Called


The final working solution for me was to leave main.js untouched, and instead:

register-service-worker (applicable portion)

import { register } from 'register-service-worker';const UpdatedEvent = new CustomEvent('swUpdated', { detail: null });if (process.env.NODE_ENV === 'production') {  register(`${process.env.BASE_URL}service-worker.js`, {    updated (registration) {      console.log('New content is available; please refresh.');      UpdatedEvent.detail = registration;      document.dispatchEvent(UpdatedEvent);    },  });}

App.vue (applicable portion)

<script>export default {  name: 'App',  data () {    return {      registration: null,    };  },  mounted () {    document.addEventListener('swUpdated', this.showRefreshUI);  },  beforeDestroy () {    document.removeEventListener('swUpdated', this.showRefreshUI);  },  methods: {    showRefreshUI (e) {      this.registration = e.detail;      // My code to show the refresh UI banner/snackbar goes here.    },  },};</script>


I'm not sure but I think you could use a custom event for this purpose. Something like this might work for you ..

1) Create the custom event in your main.js ..

main.js

import Vue from 'vue';import App from './App';import './registerServiceWorker';const updateEvent = new Event('SWUpdated');new Vue({  router,  render: h => h(App),}).$mount('#app');

2) Dispatch the custom event when the service worker is updated ..

register-service-worker

import { register } from 'register-service-worker';if (process.env.NODE_ENV === 'production') {  register(`${process.env.BASE_URL}service-worker.js`, {    updated (registration) {      console.log('New content is available; please refresh.');      document.dispatchEvent(updateEvent);    },  });}

3) Attach an event listener to the document object in your mounted hook that listens for your custom event. Remove the event listener in the beforeDestroy hook ..

App.vue

<script>export default {  name: 'App',  mounted () {    document.addEventListener('SWUpdated', this.showRefreshUI);  },  beforeDestroy () {    document.removeEventListener('SWUpdated', this.showRefreshUI);  },  methods: {    showRefreshUI () {      // My code to show the refresh UI banner/snackbar goes here.    },  },};</script>