Service worker通知承诺被破坏

Service worker notification promise broken?

本文关键字:承诺 worker 通知 Service      更新时间:2023-09-26

从MDN中我看到showNotification返回一个承诺,应该解析为NotificationEvent

<标题> 语法

ServiceWorkerRegistration.showNotification(标题、).then(function(NotificationEvent){…});

返回

解析为NotificationEvent的Promise。

然而,我在这里设置了它,通知正在发送,但如果你看一下控制台,你会注意到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是未定义的,我真的不知道该怎么做。

我做错了什么吗?

我不知道你说的get hold on notification是什么意思?如果您希望在用户单击通知时捕获事件,则可以通过添加侦听器来实现。

add return。

return registration.showNotification('Laff', {

捕捉notificationClick上的事件:

    self.addEventListener('notificationclick', function (event) {
        var tag = event;
}

希望有所帮助

文档中确实有一个问题,showNotification方法没有返回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