Many applications today inform users about important messages related to their application by sending notifications – this can be via push or web. With a web notification, a user can click on the notification and instantly get back to the application to further act on that piece of content.
For the Stream messaging platform, one of the use cases could be sending a notification when a new message arrives, just like you have with Slack, WhatsApp, Facebook Messenger, etc.
In this post, you will learn how to use the Web Notification API – a web spec – to display notifications when new messages arrive within your application.
Preparing the Project
We're going to work with a React project as an example. To do that, we will need to clone a simple React project from GitHub. This project accompanies a tutorial on building conversational UI applications with React and Stream Chat. Open your command-line application and following commands in your terminal:
git clone https://github.com/pmbanugo/react-conversational-ui-tutorial.git && cd react-conversational-ui-tutorial && yarn install
Using The Notifications API
The command you ran downloaded the project and installed the dependencies required to run the application. We will make modifications to the application so that users get notified when a new message arrives.
The first thing we need to do in order to use the API properly is to ask the user for permission to allow our application to send system notifications from the browser.
By asking for permission, the Notifications API will allow the user to control which applications are allowed to display notifications, as well as which are not. When a choice has been made, the setting will generally persist for the current session and well into the future.
Request Permission
The Notifications API exposes a requestPermission()
method that is required to request permission to display notifications to a user. We will request permission when the app is loaded.
Open the project in your preferred code editor and open the src/App.js
file.
Then, add the code below to the class:
componentDidMount() {
this.askNotificationPermission();
}
askNotificationPermission = async () => {
// check if the browser supports notifications
if ("Notification" in window) {
if (this.checkNotificationPromise()) {
const permission = await Notification.requestPermission();
this.handlePermission(permission);
} else {
Notification.requestPermission(permission => {
this.handlePermission(permission);
});
}
} else {
console.log("This browser does not support notifications.");
}
};
handlePermission = permission => {
if (!("permission" in Notification)) {
Notification.permission = permission;
}
};
In the code above, we added a method called askNotificationPermission()
which is called when the component is mounted.
The askNotificationPermission()
method first checks if the browser supports the Notification API. If it does, it calls checkNotificationPromise()
to check if the browser supports the promise-based version of Notification.requestPermission()
, and based on this result, it calls either the promised-based API version or the callback-based version.
When the user responds to the permission request, we call the handlePermission(permission)
method which explicitly sets the Notification.permission
value because an old version of Chrome did not do this automatically.
We mentioned that we had to check whether the browser supports the promise-based version of Notification.requestPermission()
. We did this with a call to this.checkNotificationPromise()
method. Let's add the definition for this method:
checkNotificationPromise() {
try {
Notification.requestPermission().then();
} catch (e) {
return false;
}
return true;
}
What this method does is to call the .then()
method on Notification.requestPermission()
and then returns true if it doesn't throw an error, or return false if it does.
Show The Notification
A notification is displayed when we create a new Notification
instance using the constructor. The constructor must be passed a title
argument, and can optionally be passed an options
object to specify options such as text direction
, body text
, and more.
Let's create a method that'll be responsible for this and call that method in the onNewMessage
method.
Add a new method named createNotification
:
createNotification(message) {
return new Notification(`${message.author.name} sent a message`, {
body: message.text
});
}
This method accepts the message as an argument. It calls the Notification()
constructor with a title and uses the message text as the body text for the notification.
We will now call this method inside the onNewMessage
method. Add the code below after line 77:
if (message.author.id !== this.user.id) this.createNotification(message);
With the code you just added, the notification will only be created if the author of the message is not the currently logged in user.
Putting It All Together
Let's see how this works in the browser. We will run the React application, but we also need an API that generates a user access token for the Stream Chat client. We will use the project which you can find on https://github.com/pmbanugo/stream-chat-boilerplate-api. Follow the instruction in the README file to set up and start the application. When it has started, start the React application by running yarn start
in the command line.
That's A Wrap!
There you have it! You learned how to use the Notification API to display notifications. To use this API, you first need to get permission from the user by calling Notification.requestPermission()
and then create the notification using the Notification()
constructor, passing it a title and an options object.
The code for this tutorial is 100% open-source and available on GitHub.
For more information on how to build a messaging platform on top of Stream Chat, have a look here.
Happy coding!
Top comments (0)