Chrome桌面通知不会显示该消息

时间:2016-02-26 05:59:34

标签: google-chrome push-notification google-cloud-messaging web-push web-notifications

我正在开发一个支持桌面通知的网站。我正在使用GCM和Azure Notification Hub向最终用户发送推送消息。我遵循了这个codelab教程。在测试时,我发现推送通知确实显示在屏幕上,但是我在有效负载中写入的消息未显示在通知中。所以我再次通过了codelab,他们在body方法中提到了showNotification键。

代码

self.addEventListener('push', function(event) {
    console.log('Push message', event);
    var title = 'Push message';
    event.waitUntil(
        self.registration.showNotification(title, {
            body: 'The Message',
            icon: 'images/icon.png',
            tag: 'my-tag'
    }));
});

他们在showNotification函数中硬编码了“消息”。我不想在函数中对我的消息进行硬编码,因为我的消息总是不一样,并且会不时地变化。我想知道如何使函数在有效负载中获取消息并显示它。提前谢谢!

1 个答案:

答案 0 :(得分:0)

Chrome目前还不支持推送有效负载,目前只能在Firefox中使用它们。

解决方案是在收到通知后从服务器请求有效负载(使用fetch)。

这样的事情:

self.addEventListener('push', function(event) {
  event.waitUntil(
    fetch('./getPayload?someUniqueID=' + someUniqueID)
    .then(function(response) {
      return response.text();
    })
    .then(function(payload) {
      self.registration.showNotification('Title', {
        body: payload,
      });
    })
  );
});

显然,响应也可以是JSON,因此您可以指定所有内容(标题,正文,图标等)。

您可以在此处查看示例:https://serviceworke.rs/push-get-payload.html

另一种可能的解决方案是在有效载荷可用时使用,否则使用fetch。通过这种方式,您可以利用Firefox中的功能(以及Chrome中曾经提供的功能),并为尚不支持有效负载的浏览器提供后备支持。 Mercurius中有一个示例。

相关问题