Chrome: 通知显示事件未触发

Chrome: Notification onshow event not triggering

我正尝试在显示通知后 运行 在我的服务人员中编码。 我正在使用 API:

显示通知
self.registration.showNotification(title, options)

我尝试了一些东西:

  1. 我希望返回的承诺是用 Notification 对象实现的,然后我可以在它显示后做一些事情。但是承诺如果用 undefined.

  2. 实现
  3. 我试图附加一个这样的函数(当然是在调用 showNotification 之前):

    Notification.onshow = function() { console.log('shown')};

但未触发 (https://developer.mozilla.org/en-US/docs/Web/API/Notification/onshow)

  1. 我试图做一些类似的事情,将回调附加到 notificationclick 和 notificationclose 事件:

    self.addEventListener("notificationshow", (event) => {});

另外,没用。

我的主要 objective 基本上是在通知实例显示后获取它,这样我就可以对它做一些事情(例如调用 notifiaction.close

您可以使用 getNotifications(并按标签过滤以获取通知)

var options = { tag : 'user_alerts' };

navigator.serviceWorker.ready.then(function(registration) {
  registration.getNotifications(options).then(function(notifications) {
    // do something with your notifications
    notifications[0].close();
  }) 
});

https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/getNotifications