我正在尝试在 react js 应用程序中获取 FCM token 。
我尝试的第一件事是使用 messaging.useServiceWorker(registration)
然后使用 messaging.getToken()
它在 localhost 上的 firefox 和 google chrome 上运行良好,但在 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).
备注
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 token ?
最佳答案
我在这里找到了解决此问题的方法,这是我的代码:
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 函数。
关于javascript - 如何获得FCM token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63937976/