使用 Firebase Cloud Messaging(适用于网络),我如何生成在网页关闭或在后台显示的通知,但当我真正专注于网页时?
With Firebase Cloud Messaging (for web), how can I generate the notification that appears when the webpage is closed or in the background, but when I'm actually focused on the webpage?
据我了解,messaging.onMessage(...)
是我在页面处于焦点时处理传入消息的地方,但我似乎无法找到有关如何创建的文档通知弹出窗口就像页面在后台一样.
It's my understanding that messaging.onMessage(...)
is where I handle incoming messages when the page is in focus, but I can't seem to find documentation on how I could still create the notification pop-ups as though the page were in the background.
感谢您的宝贵时间!
通过 Notification API 处理传入消息
handle incoming messges by Notification API
messaging.onMessage(function(payload) {
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
icon: payload.notification.icon,
};
if (!("Notification" in window)) {
console.log("This browser does not support system notifications");
}
// Let's check whether notification permissions have already been granted
else if (Notification.permission === "granted") {
// If it's okay let's create a notification
var notification = new Notification(notificationTitle,notificationOptions);
notification.onclick = function(event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open(payload.notification.click_action , '_blank');
notification.close();
}
}
});
<小时>
向服务人员发送消息
send message to service worker
messaging.onMessage(function(payload) {
local_registration.active.postMessage(payload);
}
接收消息并显示来自 sw.js 的推送
receive message and show push from sw.js
self.addEventListener('notificationclick', function(event) {
console.log('[firebase-messaging-sw.js] Received notificationclick event ', event);
var click_action = event.notification.data;
event.notification.close();
// This looks to see if the current is already open and
// focuses if it is
event.waitUntil(clients.matchAll({
type: "window"
}).then(function(clientList) {
for (var i = 0; i < clientList.length; i++) {
var client = clientList[i];
if (client.url == click_action && 'focus' in client)
return client.focus();
}
if (clients.openWindow)
return clients.openWindow(click_action);
}));
});
const showMessage = function(payload){
console.log('showMessage', payload);
const notificationTitle = payload.data.title;
const notificationOptions = {
body: payload.data.body,
icon: payload.data.icon,
image: payload.data.image,
click_action: payload.data.click_action,
data:payload.data.click_action
};
return self.registration.showNotification(notificationTitle,notificationOptions);
}
messaging.setBackgroundMessageHandler(showMessage);
self.addEventListener('message', function (evt) {
console.log("self",self);
showMessage( evt.data );
})
这篇关于使用前台/焦点页面创建 Firebase 通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!