Service Worker - 为什么要延长事件的生命周期?

Service Worker -Why extend lifetime of event?

在这个例子中:

self.addEventListener('notificationclick', function(event) {
console.log('On notification click: ', event.notification.tag);
event.notification.close();

// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(clients.matchAll({
type: "window"
}).then(function(clientList) {
  for (var i = 0; i < clientList.length; i++) {
    var client = clientList[i];
    if (client.url == '/' && 'focus' in client)
    return client.focus();
  }
  if (clients.openWindow)
    return clients.openWindow('/');
}));
});

event.waitUntil() 是函数正常工作所必需的,因为它延长了事件的生命周期。但你为什么需要它?为什么不能在事件返回后简单地解决 promise?

在这种情况下,我们需要 event.waitUntil,因为 client.focusclients.openWindow 仅在作为通知点击事件的结果调用时才允许(以保护用户免受 windows未经许可擅自开放)。没有 event.waitUntil 你 运行 事件在 clients.openWindowclient.focus 被调用之前返回的风险,在这种情况下浏览器会给你这个错误:

Uncaught (in promise) DOMException: Not allowed to open a window.

查看 and the openWindow reference on MDN 的答案。