0

我正在开发一个支持桌面通知的网站。我正在利用 GCM 和 Azure 通知中心向最终用户发送推送消息。我遵循了这个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函数中硬编码了“消息”。我不想在函数中硬编码我的消息,因为我的消息不会总是相同,并且会不时变化。我想知道如何使函数在有效负载中获取消息并显示它。提前致谢!

4

1 回答 1

0

Chrome doesn't support push payloads yet, for now you could use them only in Firefox.

The solution is to request the payload from the server (using fetch) once you get a notification.

Something like this:

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

Obviously, the response can also be in JSON, so that you can specify everything (title, body, icon, etc.).

You can see an example here: https://serviceworke.rs/push-get-payload.html.

Another possible solution is to use the payload when it's available and use fetch otherwise. This way you can take advantage of the feature in Firefox (and in Chrome once available), and have a fallback for browsers that don't support payloads yet. There's an example in Mercurius.

于 2016-02-26T09:36:17.630 回答