diff --git a/client/js/webpush.js b/client/js/webpush.js index bffe65c7..81bfcb29 100644 --- a/client/js/webpush.js +++ b/client/js/webpush.js @@ -8,6 +8,14 @@ let pushNotificationsButton; let clientSubscribed = null; let applicationServerKey; +if ("serviceWorker" in navigator) { + navigator.serviceWorker.addEventListener("message", (event) => { + if (event.data && event.data.type === "open") { + $("#sidebar").find(`.chan[data-target="#${event.data.channel}"]`).click(); + } + }); +} + module.exports.hasServiceWorker = false; module.exports.configurePushNotifications = (subscribedOnServer, key) => { diff --git a/client/service-worker.js b/client/service-worker.js index 77882983..952dbeb4 100644 --- a/client/service-worker.js +++ b/client/service-worker.js @@ -45,17 +45,38 @@ self.addEventListener("notificationclick", function(event) { event.notification.close(); event.waitUntil(clients.matchAll({ + includeUncontrolled: true, type: "window", - }).then(function(clientList) { - for (var i = 0; i < clientList.length; i++) { - var client = clientList[i]; - if ("focus" in client) { - return client.focus(); + }).then((clientList) => { + if (clientList.length === 0) { + if (clients.openWindow) { + return clients.openWindow(`.#${event.notification.tag}`); } + + return; } - if (clients.openWindow) { - return clients.openWindow("."); + const client = findSuitableClient(clientList); + + client.postMessage({ + type: "open", + channel: event.notification.tag, + }); + + if ("focus" in client) { + client.focus(); } })); }); + +function findSuitableClient(clientList) { + for (let i = 0; i < clientList.length; i++) { + const client = clientList[i]; + + if (client.focused || client.visibilityState === "visible") { + return client; + } + } + + return clientList[0]; +}