Firebase Messaging Service Worker #447
Answered
by
bruceharrison1984
bruceharrison1984
asked this question in
Q&A
-
I'm trying to use the custom worker feature to setup Firebase Messaging, but it explicitly expects the service worker to be named Is there any way to specify a name? |
Beta Was this translation helpful? Give feedback.
Answered by
bruceharrison1984
Jan 5, 2023
Replies: 1 comment
-
Found an old thread that answers this question: Custom service worker: import { firebaseConfig } from '../src/firebase/FirebaseConfig';
import { getMessaging, onBackgroundMessage } from 'firebase/messaging/sw';
import { initializeApp } from 'firebase/app';
// get type file from: https://github.com/shadowwalker/next-pwa/blob/master/examples/custom-ts-worker/types/service-worker.d.ts
let self: ServiceWorkerGlobalScope;
const firebase = initializeApp(firebaseConfig);
const messaging = getMessaging(firebase);
onBackgroundMessage(messaging, async ({ notification }) => {
console.log(
'[firebase-messaging-sw.js] Received background message ',
notification,
);
await self.registration.showNotification(notification?.title!, {
body: notification?.body,
});
}); Client-side code: // after adding the service worker, the following will register the client via the next-pwa service worker
export const requestMessagingToken = async () => {
if (typeof window === 'undefined' || !('serviceWorker' in navigator))
throw new Error('Cannot call FCM on server side');
const serviceWorkers = await navigator.serviceWorker.getRegistrations();
try {
return await getToken(getMessaging(), {
serviceWorkerRegistration: serviceWorkers[0],
});
} catch (err) {
console.error('An error occurred while retrieving token. ', err);
}
}; |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
bruceharrison1984
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found an old thread that answers this question:
#156
Custom service worker: