Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FCM: firebase getToken options( ServiceWorkerRegistration, vapidKey)

So this is how the firebase docs describe the get token function:

getToken ( options ? : { serviceWorkerRegistration ?: ServiceWorkerRegistration ; vapidKey ?: string } ) : Promise < string >

Optional options: { serviceWorkerRegistration?: ServiceWorkerRegistration; vapidKey?: string }

Optional serviceWorkerRegistration?: ServiceWorkerRegistration The service worker registration for receiving push messaging. If the registration is not provided explicitly, you need to have a firebase-messaging-sw.js at your root location. See Retrieve the current registration token for more details.

I'm just trying to figure out how to use the service worker option in my code. Do I just put the file location inside of the getToken('/file-location') like this? Or do I import a function that registers my custom firebase service worker? I might just be stupid but these docs are barebones.

like image 637
Officer_Narc Avatar asked Sep 18 '25 03:09

Officer_Narc


1 Answers

If you have your firebase-messaging-sw.js in your (web)server root, you can just call .getToken(), and your service worker will be automatically loaded and used.

If you have your firebase-messaging-sw.js at /my-other-folder, then you will need to call it this way:

const swRegistration = await navigator.serviceWorker.register('/my-other-folder/firebase-messaging-sw.js');
const token = await fcm.getToken({
  serviceWorkerRegistration: swRegistration,
});
like image 165
Francesco Colamonici Avatar answered Sep 19 '25 15:09

Francesco Colamonici