我成功地注册了FCM的token来订阅一个主题并接收消息,使用下面的代码注册service worker,并获得token如下,之后它调用服务器订阅特定的主题。
const registration = await navigator.serviceWorker.register("/firebase-messaging-sw.js");
const permission = await Notification.requestPermission();
const GET_TOKEN_PARAMS = {
vapidKey: xxxxxx,
serviceWorkerRegistration: registration
};
const current_token = await getToken(messaging, GET_TOKEN_PARAMS);
return await processNewToken(current_token);
字符串
这一切工作正常最初,我能够接收消息时,上述代码运行没有问题。然而,一段时间后,我的代码停止接收消息。这是我试图解决的问题。
我发现,如果我停止“service-worker.js”并触发一条消息,我会立即看到“service-worker.js”开始运行。因此,我目前的工作假设是,当我部署更新到我的代码时,在某个时候“service-worker.js”成为消息的接收者,而不是“firebase-messaging-sw.js”。
我用来注册“service-worker.js”的代码如下。
import { register } from 'register-service-worker'
if (process.env.NODE_ENV === 'production') {
register('/service-worker.js', {
registrationOptions: { scope: './' },
ready (registration) {
console.log('Service worker is active.')
},
registered (registration) {
console.log('Service worker has been registered.')
},
cached (registration) {
console.log('Content has been cached for offline use.')
},
updatefound (registration) {
console.log('New content is downloading.')
},
updated (registration) {
console.log('New content is available; close tab then reopen.');
registration.update();
},
offline () {
console.log('No internet connection found. App is running in offline mode.')
},
error (error) {
console.error('Error during service worker registration:', error)
}
})
}
型
这是使用email protected(https://stackoverflow.com/cdn-cgi/l/email-protection)的service-worker.js是使用email protected(https://stackoverflow.com/cdn-cgi/l/email-protection)生成的。也使用email protected(https://stackoverflow.com/cdn-cgi/l/email-protection)
任何帮助非常感谢,因为这是目前对我来说是一个谜。
1条答案
按热度按时间jvlzgdj91#
因此,我已经从尝试解决两个服务工作者转变为将其整合为一个服务工作者,因为到目前为止,这似乎是可行的。我将“firebase-messaging-sw.js”重命名为“service-worker.js“,在公共文件夹中,然后我在它的开头添加了以下内容:
字符串
我不得不将以下内容添加到workbox-js.js:
型
最后,我现在需要调用“workbox injectManifest workbox-js”,而不是调用“workbox generateSW workbox-js”。