网络推送通知-在Chrome上多次获取相同的通知

时间:2019-07-03 13:55:32

标签: push-notification notifications web-push

我正在处理推送通知。即使我已经编写了用于关闭通知的代码,我仍然面临多次获得相同通知的问题。

self.addEventListener('push', async (event) => {
  if (event.data) {
    const [data] = event.data.json()
    const body = `Notification: ${data.timestampV} - ${data.eventType}`
    const title = 'Web Notification'
    const options = {
      body,
      icon: 'images/icon.png',
      badge: 'images/badge.png',
    }

    event.waitUntil(self.registration.showNotification(title, options))
  } else {
    console.log('This push event has no data.')
  }
})

self.addEventListener('notificationclick', function (event) {
  event.notification.close()

  // close all notifications
  self.registration.getNotifications().then(function (notifications) {
    notifications.forEach(function (notification) {
      notification.close();
    });
  });
  // eslint-disable-next-line no-undef
  clients.openWindow('/feeds')
})

谢谢。

1 个答案:

答案 0 :(得分:0)

此代码对我有用。 添加异步功能

  var newEvent = new Event('push');
  newEvent.waitUntil = e.waitUntil.bind(e);
  newEvent.data = {
    json: async function () {
      var newData = e.data.json();
      newData.notification = newData.data;
      self.registration.showNotification(newData.data.title, {
        ...newData.data,
        data: newData.data
      });
      return newData;
    },
  };

请从 https://github.com/firebase/quickstart-js/issues/71#issuecomment-396958853