【问题标题】:Service Worker to identify the WindowClient that posted a messageService Worker 识别发布消息的 WindowClient
【发布时间】:2021-05-16 23:09:32
【问题描述】:

在我的服务工作者中,我会确定触发事件的确切窗口实例。比如我特别感兴趣的两个事件是messagenotificationclick

对于消息事件

某些页面会:

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 以便将其包含在消息中/事件数据中?

【问题讨论】:

    标签: javascript service-worker


    【解决方案1】:

    窗口客户端的 id 存储在消息事件中。例如:

    const windowClient = event.source.id;
    

    我不确定 notificationclick 事件,抱歉。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-04
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多