Bobcares

WeSupport

Call Us! 1-800-383-5193
Call Us! 1-800-383-5193
Call Us! 1-800-383-5193

Need Help?

Emergency Response Time custom

Our experts have had an average response time of 11.55 minutes in January 2021 to fix urgent issues.

We will keep your servers stable, secure and fast at all times for one fixed price.

Push Notification using Firebase Cloud Messaging – How to setup

by | Feb 19, 2021

Need to setup Push Notification using Firebase Cloud Messaging(FCM)? We can 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. For this, we can use FCM.

Here at Bobcares, 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 Techs 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.bobcares.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 assistance to set up push notifications? We are happy to help you!]

Conclusion

To conclude, we saw how to set up push notification using Firebase. Also, we saw the steps that our Support Engineers follow to set up push notifications.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = "owonCMyG5nEQ0aD71QM";

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

server management

Spend time on your business, not on your servers.

TALK TO US

Or click here to learn more.

Categories:

Tags: