如何获得FCM令牌?

时间:2020-09-17 12:24:06

标签: javascript reactjs firebase google-chrome firebase-cloud-messaging

我正在尝试在React js应用程序中获取FCM令牌。 我尝试的第一件事是使用messaging.useServiceWorker(registration),然后使用messaging.getToken(),它在Firefox和google chrome的localhost上运行良好,但是在HTTPS实时服务器上,在Firefox上运行良好,但在chrome中抛出错误: DOMException: Failed to execute 'subscribe' on 'PushManager': Subscription failed - no active Service Worker

我看到了Firebase文档,发现messaging.useServiceWorker现在已过时,我不得不改用messaging.getToken({ serviceWorkerRegistration }),但它抛出一个错误: 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).

注释

  • firebase-messaging-sw.js 文件位于公共目录下。
  • firebase-messaging-sw.js 文件为空。
  • 这是我注册服务工作者的方式:

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")
  }
};

我应该怎么做才能以书面方式获得FCM令牌?

1 个答案:

答案 0 :(得分:0)

我找到了解决此问题的方法,这是我的代码:

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

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

然后我通过点击操作触发 askNotificationPermission 函数。