2024-07-01 13:11:20 +02:00
|
|
|
import { requestApi } from ':src/utils.ts'
|
2024-06-13 12:42:41 +02:00
|
|
|
|
2024-06-11 17:02:00 +02:00
|
|
|
export default function RegisterServiceWorker() {
|
2024-06-06 16:35:55 +02:00
|
|
|
if ('serviceWorker' in navigator) {
|
2024-07-16 23:52:06 +02:00
|
|
|
import(':islands/StartServiceWorker.tsx').then(async (mod) => {
|
2024-06-11 17:02:00 +02:00
|
|
|
const href = mod.default()
|
2024-06-13 12:42:41 +02:00
|
|
|
const registration = await navigator.serviceWorker.register(href, {
|
|
|
|
scope: '/',
|
|
|
|
type: 'module',
|
|
|
|
})
|
|
|
|
|
|
|
|
// Notification.requestPermission().then((permission) => {
|
|
|
|
// if (permission !== 'granted') return
|
|
|
|
|
|
|
|
// registration.showNotification('Notification permission granted', {
|
|
|
|
// body: 'Notification is ok.',
|
|
|
|
// })
|
|
|
|
// })
|
|
|
|
|
2024-07-17 02:34:22 +02:00
|
|
|
async function getSubscription() {
|
2024-06-13 12:42:41 +02:00
|
|
|
const currentSubscription = await registration.pushManager
|
|
|
|
.getSubscription()
|
|
|
|
if (currentSubscription) return currentSubscription
|
|
|
|
|
|
|
|
const applicationServerKey = await requestApi<void, string>(
|
|
|
|
'webpush/vapid',
|
|
|
|
'GET',
|
|
|
|
)
|
|
|
|
|
|
|
|
return await registration.pushManager.subscribe({
|
|
|
|
userVisibleOnly: true,
|
|
|
|
applicationServerKey,
|
|
|
|
})
|
2024-07-17 02:34:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
|
|
|
const subscription = await getSubscription()
|
|
|
|
await requestApi('webpush/subscription', 'POST', subscription)
|
|
|
|
} catch (cause) {
|
|
|
|
console.error('Push subscription is not available', { cause })
|
|
|
|
}
|
2024-06-11 17:02:00 +02:00
|
|
|
})
|
2024-06-06 16:35:55 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return <></>
|
|
|
|
}
|