if (navigator.setAppBadge) {
// The API is supported, use it.
} else {
// The API is not supported, don't use it.
}Display a badge on the app icon / notebook
Display a badge on the app icon
Runnable notebook: every JavaScript, HTML and CSS example on this page executes in a sandboxed local frame. Nothing leaves the browser.
Notification.requestPermission().then((result) => {
console.log(result);
});// Check for support first.
if (navigator.setAppBadge) {
// Display the number of unread messages.
navigator.setAppBadge(numberOfUnreadMessages);
}// Check for support first.
if (navigator.setAppBadge) {
// Just display the badge, with no number in it.
navigator.setAppBadge();
}// Check for support first.
if (navigator.clearAppBadge) {
// Remove the badge on the app icon.
navigator.clearAppBadge();
}// Listen to "push" events in the service worker.
self.addEventListener("push", (event) => {
// Extract the unread count from the push message data.
const message = event.data.json();
const unreadCount = message.unreadCount;
// Set or clear the badge.
if (navigator.setAppBadge) {
if (unreadCount && unreadCount > 0) {
navigator.setAppBadge(unreadCount);
} else {
navigator.clearAppBadge();
}
}
// It's obligatory to show the notification to the user.
self.registration.showNotification(`${unreadCount} unread messages`);
});