Push Notification using Firebase Cloud Messaging








Are you trying to set up Push Notification using Firebase Cloud Messaging(FCM)? 

This guide will help you.


We know that Push notification is one of the effective ways to increase user engagement and bring more traffic to the website.

However, if push messages pop up every now and then it may not help so we have to find a way to send push messages in a timely manner. 

To do this, we can use FCM.

Here at Ibmi Media, we get requests from our customers to set up push notifications as a part of our Server Management Services.

Today let's see how our Support Experts set up push notifications using Firebase.


Steps to set up Push Notification using Firebase

Here we will need a Firebase account and a website as prerequisites for the setup.


The steps that our Support techs follow to setup push notification using Firebase are given below:

1. Register Firebase account

a) Firstly, for signing up we can use our google account. Once we sign in we will be able to see the Firebase console page.

b) After that we will go to the Firebase site and click on Firebase Console.

c) Then click on Add project.


2. Getting Project credentials info

a) First we will go to project settings.

b) Then take the project overview.

c) After that we will click on Cloud messaging tab.

d) From here we will copy the server ID and Server API keys.


3. Creating service worker JS and initializing Firebase

a) We will create a file named firebase-messaging-sw.js and add the following code and place it to the root of the web folder.

This will create a service worker:

importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
firebase.initializeApp({
'messagingSenderId': 'YOUR-SENDER-ID',
'apiKey': 'YOUR_API_KEY',
'projectId': 'YOUR_PROJECT_ID',
});
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: 'https://cdn.linuxapt.com/logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});


4. Requesting permission from the device

Next, we will make a request to user explicitly to the user for sending a notification as a part of the privacy policy:

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);
});


5. Getting device Token

Once the user grants permission to send the notification, we will get an FCM registration token that can be used to send push messages to the user:

const messaging = firebase.messaging();
 messaging
   .requestPermission()
   .then(function () {
     MsgElem.innerHTML = "Notification permission granted." 
     console.log("Notification permission granted.");
     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);
 });


6. Adding all the scripts to the HTML file.

We can add the following HTML code to a file:

<html>
<title>Firebase Messaging Demo</title>
<style>
div {
margin-bottom: 15px;
}
</style>
<body>
<div id="token"></div>
<div id="msg"></div>
<div id="notis"></div>
<div id="err"></div>
<script src="https://www.gstatic.com/firebasejs/4.6.2/firebase.js"></script>
<script>
MsgElem = document.getElementById("msg")
TokenElem = document.getElementById("token")
NotisElem = document.getElementById("notis")
ErrElem = document.getElementById("err")
var config = {
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
MsgElem.innerHTML = "Notification permission granted."
console.log("Notification permission granted.");
return messaging.getToken()
})
.then(function(token) {
TokenElem.innerHTML = "token is : " + token
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
console.log("Unable to get permission to notify.", err);
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
NotisElem.innerHTML = NotisElem.innerHTML + JSON.stringify(payload)
});
</script>
<body>
</html>


7. Testing Push message

After completing the setup,  we will try sending a test push notification.

For this, we will navigate to the Notification composer section in the firebase console and follow the steps mentioned below:

1. Open the Notifications composer and select New notification.

2. Enter the message text.

3. Select Send test message.

4. In the field labeled Add an FCM registration token, enter the registration token.

5. Finally, we can click Test


[Need urgent assistance to set up push notifications? We are happy to help you! ]



Conclusion

This article will guide you on steps to set up push notifications. Also, you will learn how to set up push notification using Firebase.  

#Firebase #Notifications is a free service that enables user notifications for Android and iOS devices. These notifications can be directed at your individual users; to topics that they subscribe to; or to segments defined by analytics audiences.

Notification messages are handled by the FCM SDK automatically and displays the message to end-user devices on behalf of the client app. Notification messages have a predefined set of user-visible keys and an optional data payload of custom key-value pairs.

To the end user, push notifications may not seem noticeably different from marketing communications via SMS or email. 

However, from a mobile app's end, push notifications are an enormous improvement in terms of reliability and sophistication to SMS.

To check my firebase push notifications:

1. #Install and run the app on the target device.

2. Make sure the app is in the background on the device.

3. Open the Notifications composer and select New notification.

4. Enter the message text.

5. Select Send test message.


For Linux Tutorials

We create Linux HowTos and Tutorials for Sys Admins. Visit us on LinuxAPT.com

Also for Tech related tips, Visit forum.outsourcepath.com or General Technical tips on www.outsourcepath.com