This tutorial is designed to guide you through the process of handling and displaying notifications within your application. Notifications are a vital part of many applications, providing real-time updates and alerts to users.
By the end of this tutorial, you will be able to:
- Display notifications to users
- Handle user interactions with these notifications
The only prerequisite for this tutorial is a basic understanding of JavaScript and HTML.
Notifications are alerts that appear outside of the app's interface. They provide short, timely information about events in the app while it's not in use.
To display notifications, we will use the Notification API
provided by modern browsers.
Handling user interactions on notifications varies based on the interaction type (click, close, etc.). For simplicity, we will focus on the click event in this tutorial.
Here is a simple example of how to display a notification:
// Request permission to display notifications
Notification.requestPermission().then(function(result) {
if (result === 'granted') {
var notification = new Notification('Hello, world!');
}
});
This code first requests permission from the user to display notifications. If the user grants permission, a new notification is displayed with the message "Hello, world!".
Now, let's handle the click event on the notification:
Notification.requestPermission().then(function(result) {
if (result === 'granted') {
var notification = new Notification('Hello, world!');
notification.onclick = function(event) {
event.preventDefault(); // prevent the browser from focusing the Notification's tab
window.open('https://www.example.com', '_blank');
}
}
});
Here, when a user clicks on the notification, the browser opens a new tab with the URL 'https://www.example.com'.
In this tutorial, you learned how to display notifications to users and handle their interactions with these notifications.
Next, you might want to learn how to customize notifications with images and action buttons. You can find more detailed information on the MDN Notification API page.
Display a notification with the title "New message" and the body "You have a new message from John". Test your code to make sure it works.
Modify the notification from the previous exercise to open your email client when clicked.
Solutions:
Notification.requestPermission().then(function(result) {
if (result === 'granted') {
var notification = new Notification('New message', {
body: 'You have a new message from John'
});
}
});
Notification.requestPermission().then(function(result) {
if (result === 'granted') {
var notification = new Notification('New message', {
body: 'You have a new message from John'
});
notification.onclick = function(event) {
event.preventDefault();
window.open('mailto:', '_blank');
}
}
});
For further practice, try to add more features to your notifications, like icons, vibration patterns, or custom sounds.