Angular中firebase-messaging-sw.js无法用import,如何实现onBackgroundMessage?
解决方案
你当前的问题根源是Service Worker环境不支持ES模块的import语法,官方示例的模块写法需要配合特定构建配置,直接在firebase-messaging-sw.js中使用import必然报错。以下是基于你现有兼容脚本的可行修改方案:
修改后的firebase-messaging-sw.js代码
importScripts("https://www.gstatic.com/firebasejs/9.1.3/firebase-app-compat.js"); importScripts("https://www.gstatic.com/firebasejs/9.1.3/firebase-messaging-compat.js"); const app = firebase.initializeApp({ apiKey: "AIzaSyAyGD0QIxpGieOtvEvFBzJMO5l5WnQxwEw", authDomain: "notifications-test-a3170.firebaseapp.com", projectId: "notifications-test-a3170", storageBucket: "notifications-test-a3170.appspot.com", messagingSenderId: "301382591226", appId: "1:301382591226:web:7646ab699982008f35df43", measurementId: "G-E58TMQZWLP", senderId: 301382591226, }); const messaging = firebase.messaging(app); // 注册后台消息监听 firebase.messaging.onBackgroundMessage(messaging, (payload) => { console.log('[firebase-messaging-sw.js] Received background message ', payload); // 自定义系统通知内容 const notificationTitle = 'Background Message Title'; const notificationOptions = { body: 'Background Message body.', icon: '/firebase-logo.png' }; self.registration.showNotification(notificationTitle, notificationOptions); });
关键注意点
- Service Worker环境默认仅支持
importScripts加载脚本,这是你前台逻辑正常、后台报错的核心原因 - Firebase v9的兼容包(
*-compat.js)保留了旧的命名空间调用方式,因此直接通过firebase.messaging.onBackgroundMessage即可注册后台消息监听 - 确保
firebase-messaging-sw.js放在Angular项目根目录(与index.html同级),保证浏览器能正确识别并注册该Service Worker
内容的提问来源于stack exchange,提问作者Azam Nawaz
相关产品推荐
相关产品推荐

