gpt4 book ai didi

javascript - 使用前景/焦点中的页面创建 Firebase 通知

转载 作者:可可西里 更新时间:2023-11-01 02:17:21 26 4
gpt4 key购买 nike

使用 Firebase Cloud Messaging(适用于网络),如何生成在网页关闭或在后台但我真正专注于网页时显示的通知?

据我了解,当页面处于焦点状态时,messaging.onMessage(...) 是我处理传入消息的地方,但我似乎无法找到有关如何创建的文档通知弹出窗口就像页面在后台一样。

感谢您的宝贵时间!

最佳答案

通过 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();
}
}
});

通知已弃用。

向service worker发送消息


   messaging.onMessage(function(payload) {
local_registration.active.postMessage(payload);
}

从 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 );
})

关于javascript - 使用前景/焦点中的页面创建 Firebase 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40411059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com