website/islands/RegisterServiceWorker.tsx

42 lines
1.1 KiB
TypeScript

import { requestApi } from ':src/utils.ts'
export default function RegisterServiceWorker() {
if ('serviceWorker' in navigator) {
import('./StartServiceWorker.tsx').then(async (mod) => {
const href = mod.default()
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.',
// })
// })
const subscription = await (async () => {
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,
})
})()
await requestApi('webpush/subscription', 'POST', subscription)
})
}
return <></>
}