Подтвердить что ты не робот

Создать уведомление Firebase со страницей на переднем плане/фокусе

С Firebase Cloud Messaging (для Интернета), как я могу сгенерировать уведомление, которое появляется, когда веб-страница закрыта или находится в фоновом режиме, но когда я на самом деле сосредоточен на веб-странице?

Я понимаю, что messaging.onMessage(...) - это то, где я обрабатываю входящие сообщения, когда страница находится в фокусе, но я не могу найти документацию о том, как я могу создавать всплывающие окна уведомлений, как если бы страница была в задний план.

Спасибо за ваше время!

4b9b3361

Ответ 1

обрабатывать входящие сообщения с помощью 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 check whether notification permissions have already been granted
    else if (Notification.permission === "granted") {
        // If it okay let create a notification
        var notification = new Notification(notificationTitle,notificationOptions);
        notification.onclick = function(event) {
            event.preventDefault(); // prevent the browser from focusing the Notification tab
            window.open(payload.notification.click_action , '_blank');
            notification.close();
        }
    }
});

Уведомление устарело.

отправить сообщение сервисному работнику


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

получить сообщение и показать push от 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 );
})

Ответ 2

Более чистый подход будет:

messaging.onMessage(payload => {
  const {title, ...options} = payload.notification;
  navigator.serviceWorker.ready.then(registration => {
    registration.showNotification(title, options);
  });
});