Web推送通知未显示

问题描述

注册了一名服务人员,并试图在浏览器中测试Web通知。 Chrome(和Firefox)声称服务工作者已成功注册

enter image description here

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

enter image description here

在我的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',})
})