SvelteKit集成Firebase Messaging遇Service Worker注册404错误
问题描述
完整错误信息
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'): A bad HTTP response code (404) was received when fetching the script. (messaging/failed-service- worker-registration). at it.<anonymous> (window-controller.ts:166:27) at tslib.es6.js:100:23 at Object.throw (tslib.es6.js:81:53) at i (tslib.es6.js:72:64)
现有文件内容
src/service-worker.js
importScripts("https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js") importScripts("https://www.gstatic.com/firebasejs/8.2.7/firebase-messaging.js") firebase.initializeApp({ apiKey: '...', authDomain: '...', projectId: '...', storageBucket: '...', messagingSenderId: '...', appId: '...', }) const messaging = firebase.messaging()
src/firebase-messaging-sw(文件名缺少.js后缀)
importScripts("https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js") importScripts("https://www.gstatic.com/firebasejs/8.2.7/firebase-messaging.js") firebase.initializeApp({ 'messagingSenderId': "..." }) const messaging = firebase.messaging() if ('serviceWorker' in navigator) { navigator.serviceWorker.register('../firebase-messaging-sw.js') .then(function (registration) { console.log('Registration successful, scope is:', registration.scope); }).catch(function (err) { console.log('Service worker registration failed, error:', err); }); }
src/jsconfig.json
"include": [ "src/**/*.d.ts", "src/**/*.js", "src/**/*.svelte", "src/firebase-messaging-sw.js" ]
Firebase消息调用代码
messaging .requestPermission() // 请求用户允许网站发送通知 .then(res => { console.log('Notification permission granted.', res) if (messaging.getToken()) { // 此Promise状态为rejected且处于pending console.log('Token will come.', messaging.getToken()) } return messaging.getToken() }) .then(token => { console.log(`token`, token) }) .catch(error => { // 错误从这里抛出 console.log('error under got token.', error) }) .catch(function (err) { errorElement.innerHTML = ErrElem.innerHTML + '; ' + err console.log('Unable to get permission to notify.', err) })
当前尝试与现象
- 已将
firebase-messaging-sw.js添加到jsconfig.json - Chrome网络标签显示
firebase-messaging-sw处于pending状态,大小0字节 - Firebase在项目根目录查找
firebase-messaging-sw.js时返回404,文件无法被找到
解决方案
1. 修正文件名后缀
直接把src目录下的firebase-messaging-sw改名为**firebase-messaging-sw.js**——目前配置和代码里都用的带后缀的文件名,实际文件缺后缀,这是最直接的404原因。
2. 确保文件能被访问到根目录
Firebase默认会去网站根目录(比如http://localhost:3000/)找这个Service Worker文件,现在你的文件在src里,需要让构建工具把它放到根路径:
- 用Vite的话,直接把
firebase-messaging-sw.js移到项目根目录的public文件夹,Vite会自动把public里的文件同步到开发/构建产物的根路径。 - 用Webpack的话,安装
CopyWebpackPlugin,配置把src/firebase-messaging-sw.js复制到输出目录的根路径。
3. 删除Service Worker内的重复注册代码
firebase-messaging-sw.js本身就是Firebase专用的Service Worker,不需要在里面再写注册逻辑,直接删掉这段冗余代码:
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('../firebase-messaging-sw.js') .then(function (registration) { console.log('Registration successful, scope is:', registration.scope); }).catch(function (err) { console.log('Service worker registration failed, error:', err); }); }
4. (可选)手动指定Service Worker路径
如果不想把文件移到根目录,就在网页的初始化脚本里手动告诉Firebase文件位置:
// 注意:这段代码写在网页脚本里,不是Service Worker文件中! import { getMessaging, registerServiceWorker } from "firebase/messaging"; const messaging = getMessaging(); registerServiceWorker(messaging, '/src/firebase-messaging-sw.js') .then((registration) => { console.log('Service worker registered'); }) .catch((error) => { console.error('Registration failed:', error); });
5. 验证文件可访问
改完配置重启开发服务器,直接在浏览器访问http://localhost:3000/firebase-messaging-sw.js,能看到文件内容且返回200状态码,就说明路径配置没问题了。
内容的提问来源于stack exchange,提问作者monsto
相关产品推荐
相关产品推荐

