4

I'm trying to implement a custom built service worker into my Nuxt JS site. I'm getting an error after generating the site as follows:

Cannot read property 'register' of undefined
function Notify (siteOptions) {
  /* Set Dependancies */
  this.siteOptions = siteOptions /* Register Applicant */
  this.register()
} /** * Register Service Worker */
Notify.prototype.register = function () {
  /** * Test Registration */
  navigator.serviceWorker.register('Notify-service-worker.js').then(function (registration) {
    console.log('SW: Available')
  }).catch(function (error) {
    console.error('SW: Not Available', error)
  })

It appears that this is the line causing issues:

navigator.serviceWorker.register('Notify-service-worker.js')

Ryan H
  • 2,620
  • 4
  • 37
  • 109
  • Serve your page over HTTPS or use localhost. Service workers require a Secure Context. https://stackoverflow.com/a/52300901/194717 – Tony Jan 16 '21 at 18:40

2 Answers2

4

It's a best practice to check whether service workers are supported in the current browser prior to registering:

<script>
    if ('serviceWorker' in navigator) {
         window.addEventListener('load', function () {
         navigator.serviceWorker.register('/service-worker.js');
         });
    }
</script>
Ashraf Sada
  • 4,527
  • 2
  • 44
  • 48
Jeff Posnick
  • 53,580
  • 14
  • 141
  • 167
2

The problem could be that service workers work only on https. I solved it by using "Localhost:3000" in the address instead of the IP.

Otherwise, you can go to chrome://flags/#unsafely-treat-insecure-origin-as-secure and click on enabled and add the application localhost link!

Dawit Abraham
  • 1,616
  • 15
  • 19