I can not register my service worker using VUE

Viewed 3055

I'm trying to create a PWA with VUE.

When trying to register the service worker I do it in the file main.js in the following way:

main.js

import Vue from 'vue'
import App from './App.vue'
import router from './router'

Vue.config.productionTip = false

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

const prod = process.env.NODE_ENV === 'production';
const swLocation = '../public/sw-config.js';

if (
  prod &&
  ('https:' === location.protocol || location.host.match(/(localhost|127.0.0.1)/)) &&
  navigator.serviceWorker
) {
  navigator.serviceWorker.register(swLocation).catch( error => console.log)
  console.log('sw register');
}

As you can see my service worker file is called sw-config.js that is in the public folder at the same level as the index.html.

But at the moment of executing npm run build and executing this from a local server with npm http-server I get the message by console: "sw register" But also the following errors:

A bad HTTP response code (404) was received when fetching the script. Failed to load resource: net::ERR_INVALID_RESPONSE

I also noticed that this error is not shown in the console the first time the application is executed but if it is reloaded it is when it starts.

I tried to fix it by cleaning all the registered service workers to verify if that was the error but it did not work, this was the code that I used in the Chrome console:

navigator.serviceWorker.getRegistrations().then(function(registrations) { for(let registration of registrations) { registration.unregister() } })

On Chrome Developer Tools I have this:

Chrome=>Dev Tools=>Application=>Service Workers=>Update on reload (selected)

I do not know how to avoid that error in the console, could someone help me?

Thanks!

Errors on Console

1 Answers

Everything in public folder is in the root folder of the application after the build.

So your url should be: const swLocation = '/sw-config.js';

Related