Derek
Derek

Reputation: 503

Create Firebase notification with page in foreground/focus

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?

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.

Thanks for your time!

Upvotes: 19

Views: 16029

Answers (3)

cristi804
cristi804

Reputation: 151

Since Notification is deprecated in Android, you should use Firebase serviceWorker registration to show the notification.

As of Feb 2020, it looks like Firebase registers its serviceWorker with the '/firebase-cloud-messaging-push-scope' scope (as can be seen in chrome devtools -> Application -> Service Workers)

To use that, you can do:

messaging.onMessage(function(payload) {
    console.log("onMessage: ", payload);
    navigator.serviceWorker.getRegistration('/firebase-cloud-messaging-push-scope').then(registration => {
        registration.showNotification(
            payload.notification.title,
            payload.notification
        )
    });
});

Upvotes: 14

wai yu
wai yu

Reputation: 343

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

Notification is deprecated.

send message to service worker


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

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

Upvotes: 33

mqklin
mqklin

Reputation: 2048

More clean approach would be:

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

Upvotes: 3

Related Questions