Service Worker - 等待 clients.openWindow 完成,然后再发布消息



我正在使用服务工作者来处理后台通知。当我收到一条消息时,我正在使用self.registration.showNotification(title, { icon, body })创建新Notification。我正在使用self.addEventListener('notificationclick', ()=>{})监视通知上的单击事件。单击时,我正在检查是否有任何WindowClient处于打开状态,如果是,我将获得其中一个窗口客户端并在其上调用postMessage以将数据从通知发送到应用程序以允许应用程序处理通知。如果没有打开的窗口,我会调用openWindow,一旦完成,我就会使用postMessage将数据发送到该窗口。

event.waitUntil(
clients.matchAll({ type: 'window' }).then((windows) => {
if (windows.length > 0) {
const window = windows[0];
window.postMessage(_data);
window.focus();
return;
}
return clients.openWindow(this.origin).then((window) => {
window.postMessage(_data);
return;
});
})
);

我面临的问题是openWindow内的postMessage呼叫永远不会传递。我猜这是因为WindowClient上的postMessage调用发生在页面完成加载之前,所以 eventListener 尚未注册以侦听该消息?是吗?

如何从服务工作进程打开一个新窗口并将消息发布到该新窗口。

我也偶然发现了这个问题,使用超时是反模式,也可能导致延迟大于可能失败的 chrome 的 10 秒限制。

我所做的是检查是否需要打开一个新的客户端窗口。 如果我在客户端数组中没有找到任何匹配项 - 这是瓶颈,您需要等到页面加载完毕,这可能需要时间,postMessage 将不起作用。

对于这种情况,我在服务工作者中创建了一个简单的全局对象,该对象正在该特定情况下填充,例如:

const messages = {};
....
// we need to open new window 
messages[randomId] = pushData.message; // save the message from the push notification
await clients.openWindow(urlToOpen + '#push=' + randomId);
....

在加载的页面中,在我的例子中是 React 应用程序,我等待我的组件挂载,然后我运行一个函数来检查 URL 是否包含"#push=XXX"哈希,提取随机 ID,然后消息传递回服务工作者向我们发送消息。

...
if (self.location.hash.contains('#push=')) {
if ('serviceWorker' in navigator && 'Notification' in window && Notification.permission === 'granted') {
const randomId = self.locaiton.hash.split('=')[1];
const swInstance = await navigator.serviceWorker.ready;
if (swInstance) {
swInstance.active.postMessage({type: 'getPushMessage', id: randomId});
}
// TODO: change URL to be without the `#push=` hash ..
}

最后在服务工作线程中,我们添加一个消息事件侦听器:

self.addEventListener('message', function handler(event) {
if (event.data.type === 'getPushMessage') {
if (event.data.id && messages[event.data.id]) {
// FINALLY post message will work since page is loaded
event.source.postMessage({
type: 'clipboard',
msg: messages[event.data.id],
});
delete messages[event.data.id];
}
}
});

messages我们的"全局"不是持久的,这很好,因为我们只需要当服务工作者在推送通知到达时"唤醒"时

。呈现的代码是代码,指向是为了解释这个想法,这对我有用。

clients.openWindow(event.data.url).then(function(windowClient) {
// do something with the windowClient.
});

我遇到了同样的问题。我的错误是我在窗口上注册了事件处理程序。但它应该像这样在服务工作者上注册:

// next line doesn't work
window.addEventListener("message", event => { /* handler */ });
// this one works
navigator.serviceWorker.addEventListener('message', event => { /* handler */ });

请参阅这些页面中的示例:
https://developer.mozilla.org/en-US/docs/Web/API/Clients
https://developer.mozilla.org/en-US/docs/Web/API/Client/postMessage

UPD:为了澄清,此代码进入新打开的窗口。在铬v.66中检查。

相关内容

最新更新