【问题标题】:ServiceWorker Push Notification options not passing to notificationServiceWorker 推送通知选项未传递到通知
【发布时间】:2020-09-19 07:26:18
【问题描述】:

我传递给我的通知的通知选项没有传递给通知,我收到的是默认通知。 (标题为网站,正文为“网站已在后台更新”)。

Service Worker 是经过改编的 create-react-app 服务工作者。

此外,推送事件处理程序中的 console.log 语句不会传递给浏览器。这是为什么呢?

推送事件侦听器直接在 CRA Service Worker 中的加载事件侦听器之后

Web-Push API 调用以创建 web-push 通知:

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:contact@email.com',
        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);
  }
});

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
        )
      );
    });

谢谢

【问题讨论】:

    标签: javascript reactjs progressive-web-apps service-worker web-push


    【解决方案1】:

    尝试像这样转换数据

    data = event.data.json();
    

    你可以阅读更多here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-06
      • 1970-01-01
      • 2016-08-07
      • 2022-06-19
      • 2011-08-23
      • 1970-01-01
      相关资源
      最近更新 更多