J.Porras
J.Porras

Reputation: 69

FCM Web - Same foreground and background notification (reuse background notification in foreground)

I would like to know if it's possible to show the same notification when my website is in foreground, as when it is in background. I don't want to personalize the looks of the notification, I want to reuse it exactly how it is.

Right now, I'm handling the arrival of the notification using this function:

function messageReceived(payload) {
    // TODO implement actions on message received
    console.log(payload);
}

But I don't want to do it. Deleting this function doesn't help.

Upvotes: 3

Views: 1441

Answers (2)

cristi804
cristi804

Reputation: 151

To work on Android, notifications have to be sent from the serviceWorker.

To get the Firebase serviceWorker registration and use that to show the notification, 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: 0

J.Porras
J.Porras

Reputation: 69

I'm not sure if there is another way to solve this, but I just created a new notification and used the payload received in the messageReceived method:

function messageReceived(payload) {    
  var notificationOptions = {
    body: payload.notification.body,
    icon: payload.notification.icon,
    click_action: payload.notification.click_action
  };
  new Notification(payload.notification.title, notificationOptions);
}

Upvotes: 3

Related Questions