Override web Firebase cloud messaging background notification with custom behavior

Viewed 371

I have a Firebase web project with a service worker that handles background notifications. By default, Firebase displays any background notifications sent to the user. I want to prevent this from happening, so I can show a different message based off the received message. I tried doing this:

import { FirebaseOptions, initializeApp } from 'firebase/app';
import { getMessaging, onBackgroundMessage } from 'firebase/messaging/sw';

const firebaseOptions: FirebaseOptions = {
    // Firebase config
};

initializeApp(firebaseOptions);

const messaging = getMessaging();

onBackgroundMessage(messaging, () => {
    self.registration.showNotification('Overriden message');
});

Right now, the device shows both the message received from the server, and the overridden message. I would like it to only show the overridden message so I can customize the behavior. How can I do this?

1 Answers

Apparently "notification" fields in your HTTP send request take precedence over any values specified in the service worker (source)

Try encapsulating the notification field in your request with a data field so that

"notification": {
  "title": "hello",
  "body": "world"
}

Becomes:

"data": {
  "notification": {
    "title": "hello",
    "body": "world"
  }
}

If that doesn't work for you, there are some other workarounds you can try here.

Related