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
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)
})
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With