我在使用 firebase 实现通知时遇到问题。点击事件不起作用。我正在使用 HTTP 1 版本发送不记名令牌。
{
"message": {
"token": "8888****usertoken****8888",
"notification": {
"title": "Background Message Title",
"body": "Background message body"
},
"webpush": {
"fcm_options": {
"link": "https://dummypage.com"
}
}
}
}
我还尝试过 click_action、action 和许多其他变体,但都不起作用。
我使用的是8.0.0版本
根据此链接上找到的文档https://firebase.google.com/docs/cloud-messaging/js/send-multiple https://firebase.google.com/docs/cloud-messaging/js/send-multiple,我应该能够使用 fcm_options 来实现它。
我尝试了一种实现 messages.onBackgroundMessage 的解决方法,但是当我实现此方法并使用 self.registration.showNotification 时,通知会显示两次。一个由浏览触发,另一个由此代码触发。
注册 self.addEventListener('notificationclick' 似乎仅在我实现 onBackgroundMessage 时才起作用。
我遵循了文档,但这让我发疯。
这是我的服务人员代码:
importScripts('https://www.gstatic.com/firebasejs/8.0.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/8.0.0/firebase-messaging.js');
var firebaseConfig = {
apiKey: "xxxxxx",
authDomain: "xxxxxxxx.firebaseapp.com",
databaseURL: "https://xxxxxx.firebaseio.com",
projectId: "xxx-xxx",
storageBucket: "xxx-xxx.appspot.com",
messagingSenderId: "222222222",
appId: "1:2222:web:22222"
};
console.log("fire base messaging")
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function (payload) {
console.log("onBackgroundMessage", payload)
var dataFromServer = payload.notification;
var notificationTitle = dataFromServer.title;
var notificationOptions = {
body: dataFromServer.body,
image: dataFromServer.image,
data: {
url: "https://google.com"
}
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
////Code for adding event on click of notification
self.addEventListener('notificationclick', function (event) {
console.log("notificationclick", event)
var urlToRedirect = event.notification.data.url;
event.notification.close();
event.waitUntil(self.clients.openWindow(urlToRedirect));
});