Sending Notifications
The Notification API allows web developers to create and display desktop notifications to users.
These notifications can provide asynchronous information, even if the user has switched between tabs or moved to another application.
Before Showing Notifications
Before showing notifications, we need to request permission from the user.
The Notification API enforces two security features:
- Users must explicitly agree to receive notifications on a per-origin basis.
- Only code running in a secure context (HTTPS) can send notifications.
Request Permission
To request permission, use the Notification.requestPermission()
method:
let result = await Notification.requestPermission();
The result indicates the current permission to display notifications:
denied
: The user refuses to have notifications displayed.granted
: The user accepts notifications.default
: The user's choice is unknown (browser acts as if denied).
If users deny
permission explicitly, the browser remembers the choice, and we won't get a second chance to request permission.
If users ignore
the request, we can ask again.
Create a Notification
To create a notification, use the Notification
constructor.
const notification = new Notification(
title,
options
);
There're come custom settings that allow you config the notifications:
options.body
: A string representing the body text of the notification, which is displayed below the title. The default is the empty string.options.icon
: A string containing the URL of an icon to be displayed in the notification.options.image
: A string containing the URL of an image to be displayed in the notification.