FCM notification received twice when in the background (service worker)

Viewed 388
1 Answers

I was able to solve it with a workaround.
Override the push Event with a custom Event class then use the listnerto intercept the incoming messages and use the custom class to re-push the events but without the 'notification' key exposed so firebase won't consider it.
In this way they won't be showed twice.

messaging.onBackgroundMessage(function(payload) {
    notificationOptions = { /*...*/ };
    self.registration.showNotification("Title",notificationOptions);
});


class CustomPushEvent extends Event {
    constructor(data) {
        super('push')

        Object.assign(this, data)
        this.custom = true
    }
}

self.addEventListener('push', (e) => {
    console.log("PUSH");
    // Skip if event is our own custom event
    if (e.custom) return;

    // Keep old event data to override
    let oldNotificationWrapper = e.data

    // Create a new event to dispatch, pull values from notification key and put it in data key,
    // and then remove notification key
    let newEvent = new CustomPushEvent({
        data: {
            json() {
                let newNotificationWrapper= oldNotificationWrapper.json()
                newNotificationWrapper.data = {
                    ...newNotificationWrapper.data,
                    ...newNotificationWrapper.notification
                }
                delete newNotificationWrapper.notification
                return newNotificationWrapper
            },
        },
        waitUntil: e.waitUntil.bind(e),
    })

    // Stop event propagation
    e.stopImmediatePropagation()

    // Dispatch the new wrapped event
    dispatchEvent(newEvent)
});
Related