我正在使用 firebase 和 vue 3。我正在尝试实现通知,一切正常,但是一旦我清除存储(清除站点数据),我就无法获取通知令牌,重新加载页面有助于解决这个问题。为什么清理存储然后启动应用程序时没有令牌收据?
错误消息:检索令牌时发生错误。 DOMException:无法在“PushManager”上执行“订阅”:订阅失败 - 没有活动的 Service Worker
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/8.10.0/firebase-messaging.js')
firebase.initializeApp({...})
const messaging = firebase.messaging();
messaging.onBackgroundMessage((payload) => {
console.log(
'[firebase-messaging-sw.js] Received background message ',
payload
);
// Customize notification here
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: payload.notification.image
};
self.registration.showNotification(notificationTitle, notificationOptions);
});
const approvedNotification = async () => {
let permission = await Notification.requestPermission();
if (permission === "granted") {
getToken(messaging, { vapidKey: '...' }).then((currentToken) => {
if (currentToken) {
token.value = currentToken
console.log('token:', currentToken)
// Send the token to your server and update the UI if necessary
// ...
} else {
// Show permission request UI
console.log('No registration token available. Request permission to generate one.');
// ...
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// ...
});
} else {
// Handle denied permission
}
}
onMounted(() => {
approvedNotification()
})
`
我尝试将版本从8.10更改为更新的版本,但是获取令牌时出错,也许应该重写firebase-messaging-sw.js
我修复了错误,我必须注册服务工作者 firebase-messaging-sw.js 范围 '/firebase-cloud-messaging-push-scope' 。如果您不这样做,那么第一个是注册的 sw.js 范围“/”,只有在那之后才是我需要的范围。范围注册的顺序很重要,请记住这一点。请务必明确范围并遵循顺序。这是解决我的问题的代码:
onMounted(async () => {
onMessage(messaging, (payload) => {
alert(payload.messageId)
});
// Registering Service Worker
const serviceWorkerRegistration: any = await navigator.serviceWorker.register("/firebase-messaging-sw.js", {scope: "/firebase-cloud-messaging-push-scope"})
.catch((err) => { return console.log('[Service Worker] Registration Error:', err) })
if ('scope' in serviceWorkerRegistration) {
console.log('[Service Worker] Registered. Scope:', serviceWorkerRegistration.scope)
}
await navigator.serviceWorker.ready; // Here's the waiting
await approvedNotification()
})