Create a firebase.js
<script>
var config = {
messagingSenderId: '<replace-with-your-sender-id>'
};
firebase.initializeApp(conyou);
</script>
Now, You will have to create firebase-messaging-sw.js
and place it to the root of the web folder
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
'messagingSenderId': 'YOUR-SENDER-ID'
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/itwonders-web-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
You will also have to ask permission from the user to show a notification:
const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
MsgElem.innerHTML = "Notification permission granted."
console.log("Notification permission granted.");
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
console.log("Unable to get permission to notify.", err);
});
Retrieve the notifcation token for FCM
const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
MsgElem.innerHTML = "Notification permission granted."
console.log("Notification permission granted.");
// get the token in the form of promise
return messaging.getToken()
})
.then(function(token) {
// print the token on the HTML page
TokenElem.innerHTML = "token is : " + token
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
console.log("Unable to get permission to notify.", err);
});
You can follow this tut: Web Push Notification with Firebase