Search code examples
javascriptfirebasepush-notificationfirebase-cloud-messagingservice-worker

What is the use of firebase-messaging-sw.js in firebase web notifications?


I have configured Javascript API for firebase push notifications on my website. Everything is working fine but I'm seeing many 'Background messages'. I've just put the firebase-messaging-sw.js file in my website's directory.

I don't know the use of it. I was just trying to know what it does. If you see following code, you'll see I haven't provided the messagingSenderId still this file gets executed.

So what I want to know is:

How it works without ID?

What is the use of it? Is it a mandatory file to receive push notifications and handle them in onMessage handler?

Where should I actually put this file (my current directory is: MY-SITE-DOMAIN/firebase-messaging-sw.js but the firebase notifications are configured in different directory)?

Here's the code:

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

firebase.initializeApp({
  'messagingSenderId': 'YOUR-SENDER-ID'
});

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

  return self.registration.showNotification(notificationTitle,
     notificationOptions);
});

Original file is here


Solution

  • You can use the configuration below or just the messagingSenderID. You may have setup the config in your other javascript due to which it is not throwing any error.

    var config = {
            apiKey: "",
            authDomain: "",
            databaseURL: "",
            storageBucket: "",
            messagingSenderId: ""
        };
    

    firebase-messaging-sw.js is a must and should be present in the host root directory. This is required to setup background notification handler when browser is not in focus or in background.