push event not triggered in service worker

Viewed 288

Following this tutorial until "Handle push event" section to setup a desktop notification system in my application, I face a problem:

When I click "push" to push a notification artificially with Chrome, no notification appear. No message in the console.

I allowed the notification from the website and the service-worker is well installed in my browser.

My service worker looks like this:

self.addEventListener('push', function (event) {
  console.log('[Service Worker] Push Received.')
  console.log(`[Service Worker] Push had this data: "${event.data.text()}"`)

  const title = 'My App Name'
  const options = {
    body: event.data.text(),
    icon: 'pwa/icon.png',
    badge: 'pwa/badge.png'
  }

  const notificationPromise = self.registration.showNotification(title, options)
  event.waitUntil(notificationPromise)
})

and my service worker registration (using register-service-worker npm package) looks like this:

import { register } from 'register-service-worker'

const applicationServerPublicKey = 'BI5qCj0NdNvjDcBYTIXiNccdcP74Egtb3WxuaXrHIVCLdM-MwqPkLplHozlMsM3ioINQ6S_HAexCM0UqKMvaYmg'

function urlB64ToUint8Array (base64String) {
  const padding = '='.repeat((4 - base64String.length % 4) % 4)
  const base64 = (base64String + padding)
    .replace(/\-/g, '+')
    .replace(/_/g, '/')

  const rawData = window.atob(base64)
  const outputArray = new Uint8Array(rawData.length)

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i)
  }
  return outputArray
}

async function manageNotificationSubscription (registration) {
  const subscription = await registration.pushManager.getSubscription()
  let isSubscribed: boolean = !(subscription === null)

  if (isSubscribed) {
    console.log('User IS subscribed.')
  } else {
    console.log('User is NOT subscribed.')
    const applicationServerKey = urlB64ToUint8Array(applicationServerPublicKey)
    try {
      await registration.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: applicationServerKey
      })
      console.log('User just subscribed.')
    } catch (e) {
      console.error('Failed to subscribe the user: ', e)
    }
  }
}

if (process.env.NODE_ENV === 'production') {
  register(`${process.env.BASE_URL}service-worker.js`, {
    ready () {
      console.log(
        'App is being served from cache by a service worker.'
      )
    },
    async registered (registration) {
      console.log('Service worker has been registered.')
      await manageNotificationSubscription(registration)
    },
    cached () {
      console.log('Content has been cached for offline use.')
    },
    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)
    }
  })
}

It looks like the push event in the service-worker is not even triggered... Did I do something wrong?

0 Answers
Related