简体   繁体   English

服务人员-为什么要延长事件的生存期?

[英]Service Worker -Why extend lifetime of event?

in this example 在这个例子中

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('/');
}));
});

even.waitUntil() is necessary for the function to properly work because it extends the events' lifetime. even.waitUntil()是该函数正常运行所必需的,因为它延长了事件的生存期。 But why do you need it? 但是,为什么需要它呢? Why can't the promise simply be resolved after event has returned? 为什么在事件返回后不能简单地兑现承诺? Thank you! 谢谢!

In this case we need event.waitUntil because client.focus and clients.openWindow are only allowed when called as the result of a notification click event (to protect users from windows opening without their permission). 在这种情况下,我们需要event.waitUntil因为client.focusclients.openWindow只允许在调用时,通知点击事件的结果(以保护从Windows用户打开未经其许可)。 Without event.waitUntil you run the risk of the event returning before clients.openWindow or client.focus is called, in which case the browser will give you this error: 没有event.waitUntil运行事件之前返回的风险clients.openWindowclient.focus被调用,在这种情况下,浏览器会给你这个错误:

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

See the answer to this post and the openWindow reference on MDN . 查看答案这篇文章上MDN的openWindow参考

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM