From 988ed780fdf1b1a23dd3c82b531db67f47153837 Mon Sep 17 00:00:00 2001 From: liamcottle Date: Thu, 13 Feb 2025 19:07:09 +1300 Subject: [PATCH] open existing client if available --- src/public/service-worker.js | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/public/service-worker.js b/src/public/service-worker.js index 2b2fa34..16802a7 100644 --- a/src/public/service-worker.js +++ b/src/public/service-worker.js @@ -10,6 +10,29 @@ self.addEventListener('notificationclick', function(event) { event.notification.close(); // open pwa - event.waitUntil(self.clients.openWindow("/")); + const url = "/"; + event.waitUntil(findClientForUrl(url).then((client) => { + + // if an existing client exists, focus it + if(client){ + client.focus(); + return; + } + + // otherwise open a new window + return self.clients.openWindow(url); + + })); }); + +const findClientForUrl = function(url) { + return self.clients.matchAll({ + type: "window", + includeUncontrolled: true, + }).then(function (clientList) { + return clientList.find(function(client) { + return client.url.endsWith(url); + }); + }); +};