gpt4 book ai didi

firebase-cloud-messaging - Service Worker - 在 postMessage 之前等待 clients.openWindow 完成

转载 作者:行者123 更新时间:2023-12-04 08:44:30 25 4
gpt4 key购买 nike

我正在使用服务人员来处理后台通知。当我收到一条消息时,我正在创建一个新的 Notification使用 self.registration.showNotification(title, { icon, body }) .我正在使用 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;
});
})
);

我面临的问题是 postMessage调用 openWindow永远不会交付。我猜这是因为 postMessage调用 WindowClient在页面完成加载之前发生,所以 eventListener 还没有注册来监听该消息?是对的吗?

如何从服务人员和 postMessage 打开一个新窗口到该新窗口。

最佳答案

我也偶然发现了这个问题,使用超时是反模式,也可能导致延迟大于可能失败的 10 秒 chrome 限制。
我所做的是检查是否需要打开一个新的客户端窗口。
如果我在 clients 数组中没有找到任何匹配项 - 这是瓶颈,您需要等到页面加载完毕,这可能需要一些时间,并且 postMessage 将无法正常工作。
对于这种情况,我在服务 worker 中创建了一个简单的全局对象,该对象在特定情况下被填充,例如:

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 ..
}
最后在 service worker 中我们添加一个消息事件监听器:
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我们的“全局”不是持久的,这很好,因为当推送通知到达时服务 worker “唤醒”时我们只需要它。
提供的代码是 代码,指向 解释这个想法对我有用。

关于firebase-cloud-messaging - Service Worker - 在 postMessage 之前等待 clients.openWindow 完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49954977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com