Wrap the service worker registration logic in a try-catch block to prevent uncaught exceptions when Service Workers are not supported or fail to load. Log a debug message on failure and return null instead of propagating the error. This improves application robustness in environments without Service Worker support.
56 lines
1.5 KiB
TypeScript
56 lines
1.5 KiB
TypeScript
import { initializeApp, type FirebaseApp } from "firebase/app";
|
|
import { getMessaging, getToken, type Messaging } from "firebase/messaging";
|
|
import { VAPI_PUBLIC_KEY } from "./constants";
|
|
import { firebaseConfig } from "./firebase";
|
|
|
|
const firebase: {
|
|
app: FirebaseApp | null,
|
|
messaging: Messaging | null,
|
|
registeration: ServiceWorkerRegistration | null,
|
|
} = {
|
|
app: null,
|
|
messaging: null,
|
|
registeration: null,
|
|
};
|
|
|
|
// Initialize Firebase
|
|
export const getFirebaseApp = () => {
|
|
if (!firebase.app) {
|
|
firebase.app = initializeApp(firebaseConfig);
|
|
}
|
|
return firebase.app;
|
|
};
|
|
|
|
export const initServiceWorker = async () => {
|
|
try {
|
|
if (!navigator.serviceWorker) return;
|
|
if (!firebase.registeration) {
|
|
firebase.registeration = await navigator.serviceWorker.register('/sw.js', {
|
|
scope: '/',
|
|
});
|
|
}
|
|
console.debug('Serviceworker inited', firebase);
|
|
return firebase.registeration;
|
|
} catch(e) {
|
|
console.debug('不支持 ServiceWorker');
|
|
return null;
|
|
}
|
|
}
|
|
|
|
export const getFirebaseMessaging = () => {
|
|
if (!firebase.messaging) {
|
|
firebase.messaging = getMessaging(getFirebaseApp());
|
|
}
|
|
return firebase.messaging;
|
|
};
|
|
|
|
export async function getFirebaseToken() {
|
|
const registeration = await initServiceWorker();
|
|
if (!registeration) return '';
|
|
await registeration.update();
|
|
const token = await getToken(getFirebaseMessaging(), {
|
|
vapidKey: VAPI_PUBLIC_KEY,
|
|
serviceWorkerRegistration: registeration,
|
|
});
|
|
return token;
|
|
} |