|
|
|
|
|
|
|
|
import webPushManager from './helpers/web-push-manager'; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export type ServiceWorkerResult = { |
|
|
newContent?: boolean, |
|
|
firstCache?: boolean, |
|
|
}; |
|
|
|
|
|
const IS_PROD = process.env.NODE_ENV === 'production'; |
|
|
|
|
|
const swUrl = IS_PROD |
|
|
? `${process.env.PUBLIC_URL}/service-worker.js` |
|
|
: `${process.env.PUBLIC_URL}/push-sw-v1.js`; |
|
|
|
|
|
export default function register(): Promise<ServiceWorkerResult> { |
|
|
if ('serviceWorker' in navigator) { |
|
|
return new Promise(res => { |
|
|
window.addEventListener('load', () => { |
|
|
navigator.serviceWorker |
|
|
.register(swUrl) |
|
|
.then(registration => { |
|
|
if ('PushManager' in window) { |
|
|
webPushManager.set(registration.pushManager); |
|
|
} |
|
|
registration.onupdatefound = () => { |
|
|
const installingWorker = registration.installing; |
|
|
installingWorker.onstatechange = () => { |
|
|
if (installingWorker.state === 'installed') { |
|
|
if (navigator.serviceWorker.controller) { |
|
|
|
|
|
|
|
|
res({ newContent: true }); |
|
|
} else { |
|
|
|
|
|
res({ firstCache: true }); |
|
|
} |
|
|
} |
|
|
}; |
|
|
}; |
|
|
}) |
|
|
.catch(error => { |
|
|
console.error('Error during service worker registration:', error); |
|
|
}); |
|
|
}); |
|
|
}); |
|
|
} else { |
|
|
return Promise.resolve({}); |
|
|
} |
|
|
} |
|
|
|
|
|
export function unregister() { |
|
|
if ('serviceWorker' in navigator) { |
|
|
navigator.serviceWorker.ready.then(registration => { |
|
|
registration.unregister(); |
|
|
}); |
|
|
} |
|
|
} |
|
|
|