From 7c9455f31be4d26a125ff3a676e6a488fe3a222c Mon Sep 17 00:00:00 2001
From: Silas
Server: ${import.meta.env.VITE_BASE_URL}
API: ${import.meta.env.VITE_API_BASE_URL}
@@ -94,12 +95,18 @@ export async function subscribeUserToPush(
) {
event?.preventDefault();
try {
- const permission = await Notification.requestPermission();
- if (permission !== "granted") {
- throw new Error("Notification permission not granted");
+ notificationPermission.value = Notification.permission;
+ if (notificationPermission.value !== "granted") {
+ const permission = await Notification.requestPermission();
+
+ notificationPermission.value = permission;
}
- notificationPermission.value = permission;
+ if (notificationPermission.value !== "granted") {
+ throw new Error(
+ `Notification permission not granted: ${notificationPermission.value}`
+ );
+ }
const registration = await navigator.serviceWorker.ready;
let subscription = await registration.pushManager.getSubscription();
diff --git a/src/sw.js b/src/sw.js
index 61e54ef..4c01d00 100644
--- a/src/sw.js
+++ b/src/sw.js
@@ -24,13 +24,24 @@ self.addEventListener("push", function (e) {
}
});
-self.addEventListener("notificationclick", function (event) {
- event.notification.close();
- var url = event.notification.data.url;
- event.waitUntil(
- clients
- .openWindow(event.notification.data.url)
- .catch((err) => console.log(err))
+self.addEventListener("notificationclick", (e) => {
+ // Close the notification popout
+ e.notification.close();
+ // Get all the Window clients
+ e.waitUntil(
+ clients.matchAll({ type: "window" }).then((clientsArr) => {
+ // If a Window tab matching the targeted URL already exists, focus that;
+ const hadWindowToFocus = clientsArr.some((windowClient) =>
+ windowClient.url === e.notification.data.url
+ ? (windowClient.focus(), true)
+ : false
+ );
+ // Otherwise, open a new tab to the applicable URL and focus it.
+ if (!hadWindowToFocus)
+ clients
+ .openWindow(e.notification.data.url)
+ .then((windowClient) => (windowClient ? windowClient.focus() : null));
+ })
);
});
diff --git a/src/utils/vite-env.d.ts b/src/utils/vite-env.d.ts
index 3ec4b64..1056cdc 100644
--- a/src/utils/vite-env.d.ts
+++ b/src/utils/vite-env.d.ts
@@ -1,6 +1,6 @@
///