stacker.news/lib/badge.js
SatsAllDay 522c821c89
Notification badges (#595)
* First pass of implementing Badging API for notifications

* Only show app badge when driven from push notifications

* Display number of unread push notifications instead of just an empty badge

Clear badge via postMessage when notifications page is loaded

* de-dupe some code, update badge counter on each notification click

* remove ids, track open note count instead

* restore optional chaining

* ensure note count doesn't go below 0, and fix event.waitUntil error when clearing badge

* incorporate PR feedback
2023-11-08 18:17:01 -06:00

34 lines
1.0 KiB
JavaScript

export const CLEAR_NOTIFICATIONS = 'CLEAR_NOTIFICATIONS'
export const clearNotifications = () => navigator.serviceWorker?.controller?.postMessage({ action: CLEAR_NOTIFICATIONS })
const badgingApiSupported = (sw = window) => 'setAppBadge' in sw.navigator
const permissionGranted = async (sw = window, name = 'notifications') => {
let permission
try {
permission = await sw.navigator.permissions.query({ name })
} catch (err) {
console.error('Failed to check permissions', err)
}
return permission?.state === 'granted'
}
export const setAppBadge = async (sw = window, count) => {
if (!badgingApiSupported(sw) || !(await permissionGranted(sw))) return
try {
await sw.navigator.setAppBadge(count)
} catch (err) {
console.error('Failed to set app badge', err)
}
}
export const clearAppBadge = async (sw = window) => {
if (!badgingApiSupported(sw) || !(await permissionGranted(sw))) return
try {
await sw.navigator.clearAppBadge()
} catch (err) {
console.error('Failed to clear app badge', err)
}
}