Service Worker 通知承诺被打破?

Service worker notification promise broken?

MDN 我看到 showNotification returns 应该 解决 NotificationEvent 的承诺。

Syntax

​ServiceWorkerRegistration.showNotification(title, [options]).then(function(NotificationEvent) { ... });

Returns

A Promise that resolves to a NotificationEvent.

但是我已经设置了它 here,通知正在发送,但如果您查看控制台,您会注意到 event 未定义。

navigator.serviceWorker.register('worker.js');

Notification.requestPermission(function (result) {
    if (result === 'granted') {
        navigator.serviceWorker.ready.then(function (registration) {
            registration.showNotification('Laff', {
                body: 'Hello, you have unread mesages!',
                icon: '/apple-touch-icon.png',
                tag: 'test'
            }).then(function(event){
                console.log(event);
            });
        });
    }
});

我需要获取通知,我认为我可以从 event.notification 开始,但由于 event 未定义,我真的不知道该怎么做。

我是不是做错了什么?

我不确定您所说的保留通知到底是什么意思? 如果您希望在用户点击通知时捕获事件,您可以通过添加侦听器来实现。

添加return。

return registration.showNotification('Laff', {

在 notificationClick 上捕获事件:

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

        var tag = event;
}

希望对您有所帮助

文档中确实存在问题,showNotification 方法没有 return 一个 NotificationEvent 对象。

如果不想等待点击,可以使用getNotifications方法。这是 3 秒后关闭通知的代码。

self.registration.showNotification(...).then(() => {
    self.registration.getNotifications({tag: ...}).then(notifications => {
      setTimeout(() => notifications[0].close(), 3000);
    });
  }
})

更多信息在这里:https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/getNotifications