首页 > 解决方案 > Firebase 消息服务工作人员发送通知

问题描述

在 Firebase Messaging 文档中,有一个示例说明如何通过 javscript 文件中注册的 serviceworker 向浏览器发送通知:

messaging.onBackgroundMessage((payload) => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  // Customize notification here
  const notificationTitle = 'Background Message Title';
  const notificationOptions = {
    body: 'Background Message body.',
    icon: '/firebase-logo.png'
  };

  self.registration.showNotification(notificationTitle,
    notificationOptions);
});

但遗憾的是,没有任何例子可以为前台做同样的事情:

const messaging = firebase.messaging();

this.afMessaging.messages
        .subscribe((message) => { 
            const title = 'TEST';
            const options = {
              body: message["data"].text,
              icon: 'assets/icon.png',
              badge: 'assets/badge.png',
              actions: [
                { 
                  action: 'archive',
                  title: 'archive'
                }
              ]
            };
            
            //let notification = new Notification(title, options);
            navigator.serviceWorker.getRegistration().then(reg => reg.showNotification(title, options));

我以前用过,new Notification但这不支持动作。所以我需要使用 serviceworker 的 showNotification,但是如何从打字稿代码中访问它。
使用当前的实现,我总是会收到错误消息:

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'showNotification' of undefined
TypeError: Cannot read property 'showNotification' of undefined

标签: angularfirebasefirebase-cloud-messagingservice-worker

解决方案


推荐阅读