如何获得FCM代币



我正在尝试在react js应用程序中获取FCM令牌。我尝试的第一件事是使用messaging.useServiceWorker(registration),然后使用messaging.getToken(),对于firefox和googlechrome,它在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).

票据

  • firebasemessagingsw.js文件位于公共目录下
  • firebase消息传递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代币?

我已经找到了这个问题的解决方案,这是我的代码:

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

我正在通过单击操作启动askNotificationPermission函数。

相关内容

  • 没有找到相关文章