【问题标题】:Web push notification not showing网络推送通知未显示
【发布时间】:2020-09-16 07:18:53
【问题描述】:

我注册了一个 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


【解决方案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));
});

【讨论】:

  • event 隐式传递给函数引用。请注意,我在函数的第一行留下了一条评论,说明了我实际上是如何接收从 Chrome Devtools 推送的文本的。
  • 如果你想让服务工作者保持活跃,那么 event.waitUntil 方法必须在事件回调中初始调用,并且必须传递一个 Promise。然后,浏览器将使工作人员保持活动状态,直到 Promse 解决。因此,如果您想使用命名函数,它需要异步并在解析/拒绝时返回一个值。如果您尝试上面的示例代码会发生什么?
  • 投反对票原因:您的示例代码和问题中的代码没有区别。具体来说:示例代码中的事件处理函数也不是异步的。
【解决方案2】:

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

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

【讨论】:

猜你喜欢
  • 2019-08-06
  • 1970-01-01
  • 2016-07-22
  • 2019-05-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多