【问题标题】:How to get FCM token?如何获得 FCM 代币?
【发布时间】:2021-01-04 08:14:45
【问题描述】:

我正在尝试在 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 文件为空。
  • 这是我注册 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")
  }
};

如何以写方式获取 FCM 令牌?

【问题讨论】:

  • 你让它工作了吗?
  • @Leo 我停止了它的工作,我可能明天继续。

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


【解决方案1】:

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

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 函数。

【讨论】:

    猜你喜欢
    • 2023-03-12
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    相关资源
    最近更新 更多