【发布时间】:2021-05-16 23:09:32
【问题描述】:
在我的服务工作者中,我会确定触发事件的确切窗口实例。比如我特别感兴趣的两个事件是message和notificationclick:
对于消息事件
某些页面会:
navigator.serviceWorker.controller.postMessage('hello');
并且服务人员希望仅向该页面回复一条消息:
self.addEventListener('message', function(event) {
clients.matchAll({type: 'window'}).then(function(windowClients) {
// who sent me the message?
let windowClient = ...
windowClient.postMessage('world');
}
})
对于notificationclick事件
某些页面会:
navigator.serviceWorker.ready.then(function (reg) {
reg.showNotification('My Notification',{body: 'hi'});
});
在我的服务人员中,我想把那个窗口集中起来
self.addEventListener('notificationclick', function(event) {
event.waitUntil(
clients.matchAll({type: 'window'}).then(function(windowClients) {
// which window has created the notification?
let windowClient = ...
windowClient.focus();
}
)
})
据我所知,windowClient 本身并没有太多东西:它有一个 url 和一个 id。 我不能依赖 url,因为可能会打开同一个 url 的多个页面,但我只想对触发事件的确切窗口实例做出反应。
Id 似乎更有希望,但是如何读取页面中的 windowClient id 以便将其包含在消息中/事件数据中?
【问题讨论】: