Chrome Desktop Notification doesn't display the message

只愿长相守 提交于 2019-12-12 02:45:32

问题


I'm developing a website that supports desktop notifications. I'm utilizing GCM and Azure Notification Hub to send push messages to end users. I followed this codelab tutorial. When testing I have found that the push notifications do get displayed on the screen, but the message that I have written in the payload is not shown in the notification. So I again went through the codelab, and they have mentioned a body key in the showNotification method.

Code

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

They have hardcoded "The Message" in the showNotification function. I don't want to hardcode my message in the function since my message won't be the same always and will vary time to time. I want to know how to make the function take the message in payload and display it. Thanks in advance!


回答1:


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.



来源:https://stackoverflow.com/questions/35644593/chrome-desktop-notification-doesnt-display-the-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!