I am using service worker to handle background notifications. When I receive a message, I'm creating a new Notification
using self.registration.showNotification(title, { icon, body })
. I'm watching for the click event on the notification using self.addEventListener('notificationclick', ()=>{})
. On click I'm checking to see if any WindowClient
is open, if it is, I'm getting one of those window clients and calling postMessage
on it to send the data from the notification to the app to allow the app to process the notification. Incase there is no open window I'm calling openWindow
and once that completes I'm sending the data to that window using 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;
});
})
);
The issue I am facing is that the postMessage
call inside the openWindow
is never delivered. I'm guessing this is because the postMessage
call on the WindowClient
happens before the page has finished loading, so the eventListener is not registered to listen for that message yet? Is that right?
How do I open a new window from the service worker and postMessage to that new window.