Need help?

Our experts have had an average response time of 13.52 minutes in October 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: '/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 *

Privacy Preference Center

Necessary

Necessary cookies help make a website usable by enabling basic functions like page navigation and access to secure areas of the website. The website cannot function properly without these cookies.

PHPSESSID - Preserves user session state across page requests.

gdpr[consent_types] - Used to store user consents.

gdpr[allowed_cookies] - Used to store user allowed cookies.

PHPSESSID, gdpr[consent_types], gdpr[allowed_cookies]
PHPSESSID
WHMCSpKDlPzh2chML

Statistics

Statistic cookies help website owners to understand how visitors interact with websites by collecting and reporting information anonymously.

_ga - Preserves user session state across page requests.

_gat - Used by Google Analytics to throttle request rate

_gid - Registers a unique ID that is used to generate statistical data on how you use the website.

smartlookCookie - Used to collect user device and location information of the site visitors to improve the websites User Experience.

_ga, _gat, _gid
_ga, _gat, _gid
smartlookCookie

Marketing

Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and engaging for the individual user and thereby more valuable for publishers and third party advertisers.

IDE - Used by Google DoubleClick to register and report the website user's actions after viewing or clicking one of the advertiser's ads with the purpose of measuring the efficacy of an ad and to present targeted ads to the user.

test_cookie - Used to check if the user's browser supports cookies.

1P_JAR - Google cookie. These cookies are used to collect website statistics and track conversion rates.

NID - Registers a unique ID that identifies a returning user's device. The ID is used for serving ads that are most relevant to the user.

DV - Google ad personalisation

IDE, test_cookie, 1P_JAR, NID, DV, NID
IDE, test_cookie
1P_JAR, NID, DV
NID
hblid

Security

These are essential site cookies, used by the google reCAPTCHA. These cookies use an unique identifier to verify if a visitor is human or a bot.

SID, APISID, HSID, NID, PREF
SID, APISID, HSID, NID, PREF