Push API
The Push API allows web applications to receive messages from a server regardless of whether the application was in the foreground. Developers can send asynchronous notifications and updates to users who opt in, giving them meaningful updates and a nudge to reengage with an application.
Web applications must also have a service worker to receive push
notifications from a server. From within the service worker, push
notifications can be subscribed to using the PushManager.subscribe() method.
The Push API is available on modern versions of Chrome, Edge, and Firefox.
Notification Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { useEffect, useState } from "react";
export default function NotificationButton() {
const [canNotify, setCanNotify] = useState(false);
const onClick = async () => {
if (canNotify && Notification.permission === "granted") {
new Notification("Hi there!");
}
if (canNotify && Notification.permission !== "denied") {
const permission = await Notification.requestPermission();
if (permission === "granted") {
new Notification("Hi there!");
}
}
};
useEffect(() => {
setCanNotify("Notification" in window);
});
return canNotify ? (
<button onClick={onClick}>Click me to trigger a notification</button>
) : (
<p>Your browser doesn't support notifications.</p>
);
}
Usage
The Push API was not measured in 2021. In 2022, its first year of tracking, the API was used on 2.03% of desktop pages and 1.86% of mobile pages, making it the eighth most used capability on desktop and mobile.