PWA Push Notifications with Firebase (Cloud Messaging)-pt1
This Dot Media
Posted on September 29, 2020
Push Notification In Your PWA
Have you ever wondered how to add the famous/annoying push notifications to your app? Well, in this tutorial I'm going to show you how to do it using Firebase Cloud Messaging.
Note: This tutorial requires some basic knowledge on PWAs and Service Workers.
You can take a look to my Intro to PWA and Service Workers here
and About PWA and notifications here.
Before we begin, I need to clarify that the Notification API, and the Push API, are not the same. People get them confused all the time.
Push API: The Push API gives web applications the ability to receive messages pushed to them from a server, whether or not the web app is in the foreground, or even currently loaded, on a user agent. This lets developers deliver asynchronous notifications and updates to users that opt in, resulting in better engagement with timely new content.
Let's doooo it!!
The final code is in the FINAL branch inside of the repo.
- Clone this repo: https://github.com/devpato/pwa-FCM-notifications-tutorial
As you can see, I already have the basic structure of the app created for you, since we are only going to worry about how to send the messages via push notifications using the Firebsae Cloud Messaging service.
- Navigate to the index.html file. Notice I imported Firebase for you:
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.6.1/firebase-messaging.js"></script>
- Navigate to Firebase.com, and create an account if you don't have one.
- Once you are in the Firebase console, navigate to project settings (in case you don't have a project yet - just create it there)
- Inside of project setting, under the General tab scroll all the way down to find your Firebase SDK snippet (if it's not there yet - this means that you've created a new project, and need to add there an app. Either way, this can be done in the same place where you then will have your SDK snippet - under the General tab ). Copy paste it in a safe place. The snippet should look like this:
- Go to your index.js file, and copy paste the following after the global variables I declared for you. Replace it with your project's customized code - the snippet from step 4.
const config = {
apiKey: "XXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXXXXXXXX",
databaseURL: "XXXXXXXXXXXXXXX",
projectId: "XXXXXXXXXXXXXXX",
storageBucket: "XXXXXXXXXXXXXXX",
messagingSenderId: "XXXXXXXXXXXXXXX",
appId: "XXXXXXXXXXXXXXX",
measurementId: "XXXXXXXXXXXXXXX"
};
- Right after - initialize the firebase instance.
firebase.initializeApp(config);
- Then, we are going to create a constant called
messaging
, and will set it to firebase messaging service.
const messaging = firebase.messaging();
- Time to request permission from firebase cloud messaging. Once we get the thumbs up, they will give us a token as a promise.
messaging
.requestPermission()
.then(() => {
message.innerHTML = "Notifications allowed";
return messaging.getToken();
})
.then(token => {
tokenString.innerHTML = "Token Is : " + token;
})
.catch(err => {
errorMessage.innerHTML = errorMessage.innerHTML + "; " + err;
console.log("No permission to send push", err);
});
- Then, we are going to use the
messaging.onMessage()
method. This is used for receiving data, and notification payloads, by all users that are currently viewing the page (the page is in the foreground).
To do so, we add the following code:
messaging.onMessage(payload => {
console.log("Message received. ", payload);
const { title, ...options } = payload.notification;
});
- Notice a firebase-messaging-sw.js file. This file name is going to be searched by the Firebase SDK. The file needs to be in the ROOT of your project. The Firebase SDK will do some magic in the background to register the file as a service worker.
- Inside of your firebase-messaging-sw.js , initialize the Firebase app by passing in the messagingSenderId. The sender id can be found inside of your project settings as the following image shows.
firebase.initializeApp({
messagingSenderId: "XXXXXXX"
});
- Retrieve an instance of Firebase Messaging so that it can handle background messages.
const messaging = firebase.messaging();
- Background message handler (this one will be invoked when the page is in the backround)
messaging.setBackgroundMessageHandler(payload => {
const notification = JSON.parse(payload.data.notification);
const notificationTitle = notification.title;
const notificationOptions = {
body: notification.body
};
//Show the notification :)
return self.registration.showNotification(
notificationTitle,
notificationOptions
);
});
Test The Notification
- Run the app using any http server
- Inside of your Cloud Messaging settings (a tab in the
Firebase Console > Project Settings
), copy the server key.
- If you have a Postman http client, do the following:
POST URL:* https://fcm.googleapis.com/fcm/send *
HEADERS:Content-Type - application/jsonAuthorization - key=server_key
BODY:
{
"notification": {
"title": "Testing Notification!",
"body": "Firebase is awesome",
"click_action": "http://127.0.0.1:5501/index.html",
"icon": "http://the-link-to-image/icon.png"
},
"to": "YOUR TOKEN GOES HERE"
}
Then, click the Send button. At this point, if our app is in the foreground (it is currently opened tab in your browser), then you'll see the message we've sent in the console - handled by messaging.onMessage
.
But if it is in the background, then it will be handled by messaging.setBackgroundMessageHandler
in the service worker, and you'll see something like this:
Test your app on a real device by deploying to Firebase or any other hosting provider. If you want to host your app on the Firebase - take a look at my other tutorial.
In the next tutorials, I will show you how to successfully subscribe to notifications and push them using the Firebase console.
This Dot Labs is a modern web consultancy focused on helping companies realize their digital transformation efforts. For expert architectural guidance, training, or consulting in React, Angular, Vue, Web Components, GraphQL, Node, Bazel, or Polymer, visit [thisdotlabs.com]((https://www.thisdotlabs.com).
This Dot Media is focused on creating an inclusive and educational web for all. We keep you up to date with advancements in the modern web through events, podcasts, and free content. To learn, visit thisdot.co.
Posted on September 29, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.