mirror of
https://github.com/Tony0410/nextstep.git
synced 2026-05-24 21:31:43 +08:00
Fix service worker registration for push notifications
Instead of waiting on navigator.serviceWorker.ready (which may never resolve if registration hasn't completed), explicitly register the service worker and wait for it to activate. This fixes the "service worker not ready" error on iOS Safari PWAs. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -79,12 +79,39 @@ export function NotificationPermission({ workspaceId }: NotificationPermissionPr
|
|||||||
}
|
}
|
||||||
const { publicKey } = await keyResponse.json()
|
const { publicKey } = await keyResponse.json()
|
||||||
|
|
||||||
// Wait for service worker with timeout
|
// Ensure service worker is registered and active
|
||||||
const registrationPromise = navigator.serviceWorker.ready
|
let registration: ServiceWorkerRegistration
|
||||||
const timeoutPromise = new Promise<never>((_, reject) =>
|
|
||||||
setTimeout(() => reject(new Error('Service worker not ready - try refreshing the page')), 10000)
|
// First, try to register the service worker (in case it wasn't registered yet)
|
||||||
)
|
try {
|
||||||
const registration = await Promise.race([registrationPromise, timeoutPromise])
|
registration = await navigator.serviceWorker.register('/sw.js', { scope: '/' })
|
||||||
|
|
||||||
|
// Wait for it to be active
|
||||||
|
if (registration.installing || registration.waiting) {
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
const sw = registration.installing || registration.waiting
|
||||||
|
if (!sw) {
|
||||||
|
resolve()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const timeout = setTimeout(() => reject(new Error('Service worker activation timeout')), 10000)
|
||||||
|
|
||||||
|
sw.addEventListener('statechange', () => {
|
||||||
|
if (sw.state === 'activated') {
|
||||||
|
clearTimeout(timeout)
|
||||||
|
resolve()
|
||||||
|
} else if (sw.state === 'redundant') {
|
||||||
|
clearTimeout(timeout)
|
||||||
|
reject(new Error('Service worker became redundant'))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
} catch (regError: any) {
|
||||||
|
console.error('Service worker registration error:', regError)
|
||||||
|
throw new Error('Failed to register service worker: ' + regError.message)
|
||||||
|
}
|
||||||
|
|
||||||
// Check if push manager is available
|
// Check if push manager is available
|
||||||
if (!registration.pushManager) {
|
if (!registration.pushManager) {
|
||||||
|
|||||||
Reference in New Issue
Block a user