繁体   English   中英

网络推送通知未显示

[英]Web push notification not showing

我注册了一个 Service Worker,并尝试在浏览器中测试 Web 通知。 Chrome(和 Firefox)声称 Service Worker 已成功注册。

在此处输入图片说明

在加载 React 应用程序时,我已授予接收通知的权限。

在此处输入图片说明

在我的sw.js ,我正在侦听push事件,并尝试从 Chrome 应用程序选项卡发送示例推送消息,如上面的屏幕截图所示。

self.addEventListener("push", receivePushNotification);

在 Chrome 应用程序选项卡中单击Push时, push事件会触发,调用receivePushNotification 但是,当我尝试在浏览器中显示通知时,没有任何反应,也没有报告错误。

function receivePushNotification(event) {
  // This prints "Test push message from DevTools."
  console.log("[Service Worker] Push Received.", event.data.text());

  var options = {
    body: "This notification was generated from a push!"
  };

/*****
  I would expect the following line to display a notification, since I've already 
  granted permission to allow for notifications. Yet, nothing happens and there is 
  no error in the console.
*****/

  event.waitUntil(self.registration.showNotification("Hello world!", options));
}

您似乎在单独定义函数/未将其定义为异步函数方面走得太远了。 您也没有将事件传递给函数调用。

如果你像这样重写它会发生什么?

self.addEventListener("push", function(event) {
  console.log("[Service Worker] Push Received.", event.data.text());
  var options = {
    body: "This notification was generated from a push!"
  };
  event.waitUntil(self.registration.showNotification("Hello world!", options));
});

这是我使用的代码。 它非常通用,并且有效。

self.addEventListener('push', function (e) { 
  console.log('Push Received...')
  const data = e.data.json()
  self.registration.showNotification(data.title, {
    body: 'Notified by Waelio.com!',
    icon: 'https://picmymenu.s3.eu-west-3.amazonaws.com/waelio_logo.png',
  })
})

您可能阻止了 Chrome 通知。 如果您没有经常收到来自其他网站的通知的垃圾邮件,那么这种情况就是一个很好的提示。 这个答案对我有用。

启用 Chrome 通知

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM