Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 555
Vikas Kumar Avatar asked Feb 25 '17 11:02

Vikas Kumar


2 Answers

By default firebase will be looking for /firebase-messaging-sw.js which should contain the firebase libraries and listeners. More details here: https://firebase.google.com/docs/cloud-messaging/js/receive

If you would like to use an existing service worker, you can use https://firebase.google.com/docs/reference/js/firebase.messaging.Messaging#useServiceWorker

like this...

navigator.serviceWorker.register('/service-worker.js').then(registration => {
  firebase.messaging().useServiceWorker(registration)
})
like image 199
Phil Snell Avatar answered Oct 26 '22 17:10

Phil Snell


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.

like image 28
anshul jain Avatar answered Oct 26 '22 15:10

anshul jain