Chrome:通知onshow事件未触发

时间:2020-04-24 17:54:50

标签: javascript google-chrome notifications service-worker

显示通知后,我正在尝试在服务工作者中运行代码。 我正在使用此API显示通知:

self.registration.showNotification(title, options)

我尝试了一些东西:

  1. 我希望通过Notification对象实现返回的诺言,然后可以在显示它之后进行操作。但是诺言如果用undefined来实现。

  2. 我试图附加一个类似的函数(当然在showNotification调用之前):

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

但它没有被触发(https://developer.mozilla.org/en-US/docs/Web/API/Notification/onshow

  1. 我正在尝试做一些类似的操作,以将回调附加到notifictionclick和notificationclose事件上:

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

也没用。

我的主要目标基本上是在显示通知实例之后,以便对其进行处理(例如,调用notifiaction.close

1 个答案:

答案 0 :(得分:1)

您可以使用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