Sean Moody
Sean Moody

Reputation: 380

ServiceWorker Push Notification options not passing to notification

The notification options that I am passing to my notifications are not passing to the notification and I am getting a default notification. (Title is the website, body is "The site has been updated in the background").

Service worker is an adapted create-react-app service worker.

Also, the console.log statements in the push event handler are not passing to the browser. Why is this?

The push event listener is directly after the load event listener in the CRA Service Worker

Web-Push API Call to create a web-push notification:

router.post('/:userid', auth, async (req, res) => {
  try {
    const user = await User.findById(req.params.userid);

    user.pushSubscriptions.forEach((sub) => {
      if (sub === null) {
        return;
      }

      webpush.setVapidDetails(
        'mailto:[email protected]',
        config.get('vapidPublic'),
        config.get('vapidSecret')
      );

      const options = {
        endpoint: sub.endpoint,
        expirationTime: sub.expirationTime,
        keys: {
          p256dh: sub.keys.p256dh,
          auth: sub.keys.auth,
        },
      };

      console.log(options.endpoint);

      webpush
        .sendNotification(
          options,
          JSON.stringify({
            title: 'NotifTitle',
            body: 'Body',
          })
        )
        .catch((error) => console.log(error));
    });

    return res.status(200).json({ msg: 'Notification Sent' });
  } catch (error) {
    console.log(error);
    return res.status(500);
  }
});

Push listener in sw.js:

window.addEventListener('push', (event) => {
      console.log('Notification Recieved', event);

      //Fallback data
      let data = {
        title: 'TestABC',
        body: '123456',
      };

      if (event.data) {
        data = JSON.parse(event.data.text());
      }

      //Notification options
      var options = {
        body: data.body,
        icon: '../public/logo192.png',
        image: '../public/logo192.png',
      };

      event.waitUntil(
        console.log(options),
        navigator.serviceWorker.registration.showNotification(
          data.title,
          options
        )
      );
    });

Thanks

Upvotes: 2

Views: 1147

Answers (1)

Hakob Hakobyan
Hakob Hakobyan

Reputation: 1131

try to convert data like this

data = event.data.json();

you can read more here

Upvotes: 0

Related Questions