Skip to content
Advertisement

How to get FCM token?

I am trying to get FCM token in react js application. First thing i tried is to use messaging.useServiceWorker(registration) then use messaging.getToken() and it’s working fine on localhost for firefox and google chrome, but on an HTTPS live server it works fine on firefox but in chrome it throws an error: DOMException: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker.

I saw firebase docs and found that messaging.useServiceWorker is deprecated now and I have to use messaging.getToken({ serviceWorkerRegistration }) instead but it throws an error: FirebaseError: Messaging: We are unable to register the default service worker. Failed to register a ServiceWorker for scope ('http://localhost:3000/firebase-cloud-messaging-push-scope') with script ('http://localhost:3000/firebase-messaging-sw.js'): The script has an unsupported MIME type ('text/html'). (messaging/failed-service-worker-registration).

Notes

  • firebase-messaging-sw.js File is under the public directory.
  • firebase-messaging-sw.js File is empty.
  • This how I register the service worker:

export const registerServiceWorker = () => {
  if ("serviceWorker" in navigator) {
    return new Promise((resolve, reject) => {
      navigator.serviceWorker
      .register(process.env.PUBLIC_URL + "/firebase-messaging-sw.js")
      .then(function (registration) {
        console.log("[registration]", registration)
        
        // messaging.useServiceWorker(registration)



          resolve(registration);
        })
        .catch(function (err) {
          console.log("[ERROR registration]: ", err)
          reject(null);
        });
    });
  } else {
    console.log("SERVICE WORKER NOT IN THE BROWSER")
  }
};

What should I do to get FCM token in a write way?

Advertisement

Answer

I have found a solution for this issue here is my code:

class Firebase {
  constructor() {
    if (firebase.apps.length) return;
    firebase.initializeApp(config);
    this.auth = firebase.auth();
    this.messaging = firebase.messaging();
    navigator.serviceWorker.getRegistrations().then((registrations) => {
      if (registrations.length) {
         [this.registration] = registrations;
         return;
      }
      navigator.serviceWorker
        .register("/firebase-message-sw.js")
        .then((registration) => {
           this.registration = registration;
        });
      });
  }

  async askNotificationPermission() {
    try {
      const token = await this.messaging.getToken({
        serviceWorkerRegistration: this.registration,
      });
      return token;
    } catch (error) {
      console.error("[FIREBASE ERROR]: ", error);
      return null;
    }
  }
}

And I am firing askNotificationPermission function with a click action.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement