Adam Galiński
Adam Galiński

Reputation: 21

FCM only in foreground

It is possible to show notification only if app is on foreground? I do not need to show notifications in background. My setBackgroundMessageHandler in service worker looks like:

messaging.setBackgroundMessageHandler(function(payload) {
    console.log('[firebase-messaging-sw.js] Received background message ', payload);
    // Customize notification here
    var notificationTitle = 'Background Message Title';
    var notificationOptions = {
        body: 'Background Message body.',
        icon: '/firebase-logo.png'
    };

});

I dont return showNotification but is showing

Upvotes: 1

Views: 761

Answers (2)

Tomek Marcinkowski
Tomek Marcinkowski

Reputation: 61

To protect others from wasting their time, as I did, it is impossible to handle push events only in the foreground. (a.k.a. silent pushes are not allowed)

Even if you change the message type from notification to data, the best you'll end up with will be a generic Chrome message saying "This site has been updated in the background.".

More on this here:
https://blog.pushpad.xyz/2022/09/this-site-has-been-updated-in-the-background/

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 598603

Firebase Cloud Messaging has two types of messages:

  1. Notifications. These are handled by the system when the app is in the background, and displayed in the system drawer in that case. When your app is in the foreground, notifications are delivered to your application code.
  2. Data messages. These are always delivered to your application code, no matter if the app is in the foreground or background.

Since you want to prevent the system from displaying the notification in the system tray, you should send a data message.

Upvotes: 1

Related Questions