FireBase, Cloud Messaging

Michael Strong
4 min readFeb 24, 2019

The internet is always evolving. Service workers are a hot topic right now. Chrome and Firefox are on-board, and I’m sure Internet Explorer and Safari will follow suit soon enough. In this article we will discuss how to use Firebase and send native alerts to a device. Even if the browser is closed the notice will still arrive. It’s possible to send to 1 of your users if needed, however this article will focus on how to send to all devices subscribed.

Firebase is a back end service from Google. You can send a HTTP Post Request and it will send that message to your subscribers. Android phones, Windows Phones, and Windows Desktop (Chrome, Firefox). Service workers are not available on the iOS platforms and also do not work with Internet Explorer.

For the official docs, you can check out https://firebase.google.com/docs/cloud-messaging.

First thing you will need to do is create a Google Firebase account. This allows yyou access to their services. After a project is created you will need to copy the web setup and add it to your app.

It looks something like this.

<script src=”https://www.gstatic.com/firebasejs/5.8.4/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: “AIzaSyAt…yECVHIns_k”,
authDomain: “projectbase-c6e26.firebaseapp.com”,
databaseURL: “https://projectbase-c6e26.firebaseio.com",
projectId: “projectbase-c6e26”,
storageBucket: “projectbase-c6e26.appspot.com”,
messagingSenderId: “57747790305”
};
firebase.initializeApp(config);
</script>

In order to send alerts to the user, the user needs to allow notifications. When the user allows notifications Firebase will give you a token. If you wanted to you could POST an HTTP call and send a message to that user. Or you could add that user to a TOPIC. Once token is added to a topic you can then POST an HTTP call to the topic and the message goes out to all users.

Before we see the code that adds our website as a service worker, we will need to create a js file that serves as the service worker. Create a new file and call it firebase-messaging-sw.js. Within there add your web setup info, 2 import scripts, and declare your messaging object. Something like this:

importScripts(‘https://www.gstatic.com/firebasejs/5.8.3/firebase-app.js');
importScripts(‘https://www.gstatic.com/firebasejs/5.8.3/firebase-messaging.js');
var config = {
apiKey: “AIzaSyAt…CVHIns_k”,
authDomain: “projectbase-c6e26.firebaseapp.com”,
databaseURL: “https://projectbase-c6e26.firebaseio.com",
projectId: “projectbase-c6e26”,
storageBucket: “projectbase-c6e26.appspot.com”,
messagingSenderId: “57747790305”
};
firebase.initializeApp(config);
const messaging = firebase.messaging();

Back to the page which will allow the notice. For the user to allow notifications we can use the following code.

messaging.requestPermission()
.then(function () {
return messaging.getToken();
})
.then(function (token) {
console.log(‘Firebase:: Permission granted. Your token is ‘ + token);
})
.catch(function (err) {
console.log(‘Firebase:: Permission was denied.’);
})

Put the above on button click or page load it doesn’t matter. Once the code runs the browser and Firebase take over. The user will see a message something like this.

The token is saved to Firebase. As the programmer you could save the token and use it later for other things. This token relates to this user and this device. I recommend that you create a HTTP POST request to add that token to a topic. I used the following code.

var xhttp = new XMLHttpRequest();
xhttp.open(“POST”, “https://iid.googleapis.com/iid/info/" + token + “/rel/topics/movies”, true);
xhttp.setRequestHeader(“Authorization”, “key=AAAADXIJA…Qc4F2qytW”);
xhttp.send();

Where the key can be found within Firebase settings. Go to your Project Settings and within Cloud Messaging you will see the Server Key.

We have successfully imported Firebase into our project. We created a service worker. We got permission from the user to accept our notifications. We added the token from Firebase to a topic. You can now send out the notification. To do this you can write a HTTP POST call within your app or just use Postman. Postman is a great tool that we can use to test API calls to any service that supports HTTP requests.

You only need 2 headers and then the body. The body is in JSON format. The URL we use is.

http://fcm.googleapis.com/fcm/send

To send to 1 user you can use this as the body. Obviously change the token to your user.

{
“to”: “ek-c_hyDzco:…CgKxLaFgVWB”,
“notification”: {
“title”: “you da boss !!!”,
“body”: “worsadfsafsafsaddsafld”
}
}

To send to a topic. AKA all users, we can use the following as the body.

{
“to”: “/topics/movies”,
“notification”: {
“title”: “you da boss aaaaaaa!!!”,
“body”: “worsadfsafsafsaddsafld”,
“icon” : “/ReMag.png”
}
}

Replace the data as you see fit and if you want add an icon. To get the icon to work, as long as you push that file to your web server. It should show on the users computer.

And that's it. Happy coding!!

— javascript

--

--

Michael Strong

Living in south west Ontario Canada. Father of two. Working full time as a software engineer at a major transportation software company.