Search code examples
javascriptgoogle-chromefirebase-cloud-messaging

FCM Push notifications arrive twice if the browser is in background


I've set up a simple push notification site, the notifications arrive okay if the browser is in foreground.

The problem begins if the browser is in background: the notification arrives twice, one styled with image and other settings set and the other has only title and body message.

Content of the service worker:

importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-messaging.js');

// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
    'messagingSenderId': '...'
});

const messaging = firebase.messaging();

messaging.setBackgroundMessageHandler(function(payload) {
    console.log('[firebase-messaging-sw.js] Received background message ', 
    return null;
});

self.addEventListener('install', function (event) {
    event.waitUntil(skipWaiting());
});

self.addEventListener('activate', function (event) {
    event.waitUntil(clients.claim());
});

self.addEventListener('push', function (event) {
    var pushData = event.data.json();
    try {
        var notificationData = pushData.data;
        notificationData.data = JSON.parse(notificationData.data);
        console.log(notificationData);
        self.registration.showNotification(pushData.notification.title, notificationData);
    }
    catch (err) {
        console.log('Push error happened: ', err);
    }
});

Client side js:

firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();

messaging.onMessage(function (payload) {
    console.log("notification recieved");
    return null;
});

self.addEventListener('push', function (event) {
    console.log("window push stuff");
    return null;
});

Thanks!


Solution

  • The problem can be solved with adding this line to the messaging.setBackgroundMessageHandler event:

    self.registration.hideNotification();
    

    This way, the default notification won't show and you have to show your notification in the self.addEventListener event.