【发布时间】:2020-11-04 19:04:22
【问题描述】:
我在使用 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 上的文档,我应该可以使用 fcm_options 来实现它。
我尝试了实现messaging.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));
});
【问题讨论】:
标签: javascript firebase google-chrome push-notification firebase-cloud-messaging