网络推送通知未显示

问题描述 投票:0回答:3

我注册了一个 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));
}
javascript web push-notification service-worker web-notifications
3个回答
0
投票

我遇到了同样的问题,我看到了通知信息,但在 DevTools 中它只是说“来自 DevTools 的测试推送消息”。在这种情况下,创建您自己的小 json 通知代码并将其用于推送测试。示例 json 在这里,它对我有用。

示例 json 在这里,它对我有用。

{
"notification":{
    "title": "Angular Update",
    "data": {
        "onActionClick":{
            "default":{
                "operation": "openWindow",
                "url": "https://www.google.com/"
            }
        }
    }
}}

-1
投票

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

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

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

-1
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.