问题描述
importScripts('https://www.gstatic.com/firebasejs/8.4.3/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/8.4.3/firebase-messaging.js')
firebase.initializeApp({...config});
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
console.log('sw-fb',payload);
const notificationTitle = payload.notification.title;
const notificationoptions = {
body:"something Body",data:{...}
};
return self.registration.showNotification(notificationTitle,notificationoptions);
},
在这里,我试图显示来自 firebase 的推送通知,但是对于每个通知都会收到两个通知。第一个是默认的,第二个来自我的服务工作者。
解决方法
为了避免默认通知,通过fcm发送时需要发送如下通知数据
var payload = {
notification:{},data: {
title:'title',body:'something body',image:path,icon...},token: registrationToken
};
messaging.send(payload).then((result) => {console.log(result)})
并将 srviceworker 更新为
messaging.onBackgroundMessage((payload) => {
const { data }= payload;
const notificationTitle = data?.title;
const notificationOptions =
{ image:data.image,title:data.title,body: data.body,icon:data.icon }
self.registration.showNotification(notificationTitle,notificationOptions);
});