()
| 14 | } |
| 15 | |
| 16 | export const useWebpushNotifications = (): WebpushNotifications => { |
| 17 | const { metadata } = useEmbeddedMetadata(); |
| 18 | const buildInfoQuery = useQuery(buildInfo(metadata["build-info"])); |
| 19 | const [subscribed, setSubscribed] = useState<boolean>(false); |
| 20 | const [loading, setLoading] = useState<boolean>(true); |
| 21 | const enabled = |
| 22 | "Notification" in window && |
| 23 | "serviceWorker" in navigator && |
| 24 | !!buildInfoQuery.data?.webpush_public_key; |
| 25 | |
| 26 | useEffect(() => { |
| 27 | // Check if browser supports push notifications |
| 28 | if (!("Notification" in window) || !("serviceWorker" in navigator)) { |
| 29 | setSubscribed(false); |
| 30 | setLoading(false); |
| 31 | return; |
| 32 | } |
| 33 | |
| 34 | const checkSubscription = async () => { |
| 35 | try { |
| 36 | const registration = await navigator.serviceWorker.ready; |
| 37 | const subscription = await registration.pushManager.getSubscription(); |
| 38 | setSubscribed(Boolean(subscription)); |
| 39 | } catch (error) { |
| 40 | console.error("Error checking push subscription:", error); |
| 41 | setSubscribed(false); |
| 42 | } finally { |
| 43 | setLoading(false); |
| 44 | } |
| 45 | }; |
| 46 | |
| 47 | checkSubscription(); |
| 48 | }, []); |
| 49 | |
| 50 | const subscribe = async (): Promise<void> => { |
| 51 | try { |
| 52 | setLoading(true); |
| 53 | |
| 54 | // Explicitly request notification permission before subscribing |
| 55 | // to the push manager. Without this, pushManager.subscribe() |
| 56 | // throws a generic "Registration failed - permission denied" |
| 57 | // DOMException when the permission state is "denied", which |
| 58 | // gives no opportunity to show a clear message to the user. |
| 59 | const permission = await Notification.requestPermission(); |
| 60 | if (permission !== "granted") { |
| 61 | throw new Error( |
| 62 | "Notifications are blocked by your browser. Please allow notifications for this site in your browser settings.", |
| 63 | ); |
| 64 | } |
| 65 | |
| 66 | const registration = await navigator.serviceWorker.ready; |
| 67 | const vapidPublicKey = buildInfoQuery.data?.webpush_public_key; |
| 68 | |
| 69 | const subscription = await registration.pushManager.subscribe({ |
| 70 | userVisibleOnly: true, |
| 71 | applicationServerKey: vapidPublicKey, |
| 72 | }); |
| 73 | const json = subscription.toJSON(); |
no test coverage detected