How to call methods in Vue app $refs.components or Vuex $store from registerServiceWorker.js?

Viewed 770

I'm working on a Vue PWA scaffolded out with Vue CLI, which by default uses register-service-worker package to expose the serviceWorker lifecycle methods in registerServiceWorker.js:

ready () {
  console.log(
    'App is being served from cache by a service worker.'
  )
},
registered () {
  console.log('Service worker has been registered.')
},
cached () {
  console.log('Content has been cached for offline use.')
},
updatefound () {
  console.log('New content is downloading.')
},
updated () {
  console.log('New content is available; please refresh.')
},
offline () {
  console.log('No internet connection found. App is running in offline mode.')
},
error (error) {
  console.error('Error during service worker registration:', error)
}

registerServiceWorker.js is imported into main.js:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/index'
import './registerServiceWorker'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

The question is, how do I access scope to call methods in my Vuex $store or App.vue $refs.components from the scope of registerServiceWorker.js, e.g.

updated () {
  // Something like
  this.$store.commit('showUpdateNotification')
  // OR
  this.$refs.updateNotification.show()
}

I know I can setup additional eventListeners in my app to do this, but seems better to make use of registerServiceWorker.js?

1 Answers

Import the Vuex store in your registerServiceWorker.js file.

ie.

/* eslint-disable no-console */

import { register } from 'register-service-worker'
import appConfig from './app.config.json'
import store from './store'

if (process.env.NODE_ENV === 'production') {
  register(`${appConfig.router.baseUrl}service-worker.js`, {
    ready() {
      console.log(
        'App is being served from cache by a service worker.'
      )
    },
    cached() {
      console.log('Content has been cached for offline use.')
    },
    updated() {
      console.log('New content is available; please refresh.')
      store.commit('showUpdateNotification')
    },
    offline() {
      console.log(
        'No internet connection found. App is running in offline mode.'
      )
    },
    error(error) {
      console.error('Error during service worker registration:', error)
    },
  })
}
Related