41 lines
1,000 B
TypeScript
41 lines
1,000 B
TypeScript
'use client';
|
|
|
|
import { useEffect } from 'react';
|
|
|
|
const SW_PATH = '/sw.js';
|
|
|
|
export function ServiceWorkerProvider() {
|
|
useEffect(() => {
|
|
if (!('serviceWorker' in navigator)) {
|
|
return;
|
|
}
|
|
|
|
const registerServiceWorker = async () => {
|
|
try {
|
|
const registration = await navigator.serviceWorker.register(SW_PATH, { scope: '/' });
|
|
|
|
if (registration.waiting) {
|
|
registration.waiting.postMessage('skipWaiting');
|
|
}
|
|
|
|
navigator.serviceWorker.addEventListener('controllerchange', () => {
|
|
if (!document.hidden) {
|
|
window.location.reload();
|
|
}
|
|
});
|
|
} catch (error) {
|
|
console.error('Service worker registration failed:', error);
|
|
}
|
|
};
|
|
|
|
if (process.env.NODE_ENV === 'production') {
|
|
registerServiceWorker();
|
|
} else {
|
|
navigator.serviceWorker.getRegistration(SW_PATH).then((registration) => {
|
|
registration?.unregister();
|
|
});
|
|
}
|
|
}, []);
|
|
|
|
return null;
|
|
}
|