使用来自 Web 推送通知的数据

Use data from Push in Web Push Notifications

本文关键字:通知 数据 Web      更新时间:2023-09-26

我正在尝试使用Service Workers为Web推送通知设置演示。在服务辅助角色 sw.js 中,我有以下代码。

var title = 'Yay a message.';
var body = 'We have received a push message.';
var icon = 'icon.png';
var tag = 'simple-push-demo-notification-tag';
console.log("Hello!");
self.addEventListener('push', function(event) {
event.waitUntil(
    self.registration.showNotification(title, {
        body: body,
        icon: icon,
        tag: tag
    })
);
});

这工作正常。我希望收到我随推送cURL请求发送的数据,例如title等。有没有办法通过这种waitUntil方法获取所有这些数据?

任何帮助都非常感谢。

有两种方法:

  1. 推送有效负载(示例 https://serviceworke.rs/push-payload.html)。这更复杂,目前仅在 Firefox 和 chrome v50 中受支持。您可以将有效负载附加到推送消息,并通过事件的 data 属性 (https://developer.mozilla.org/en-US/docs/Web/API/PushMessageData) 访问它。

有效负载需要加密(https://datatracker.ietf.org/doc/html/draft-thomson-webpush-encryption-01),强烈建议使用库来处理加密细节(例如,对于 Node.js https://github.com/marco-c/web-push)。

在这种情况下,推送事件处理程序将是(假设有效负载作为 JSON 消息发送):

    var data = event.data.json();
    event.waitUntil(
      self.registration.showNotification(data.title, {
        body: data.body,
        icon: data.icon,
        tag: data.tag,
      })
    );
  1. 向服务器发出的 GET 请求以获取数据。例如,假设您的服务器返回 JSON 响应:

    event.waitUntil(
      fetch('someURL')
      .then(response => response.json())
      .then(data =>
        self.registration.showNotification(data.title, {
          body: data.body,
          icon: data.icon,
          tag: data.tag,
        })
      )
    );
    

等到 Chrome 49 问世: 2016 年 3 月 8 日

就像这篇文章中所说:https://www.chromestatus.com/features/5746279325892608,chrome将实现有效载荷