Badging for PWA app icons, Like Native Apps
Like Native Apps, The PWA Badge API allows installed web apps to set an application-wide badge on the app icon.
bash
npm install --save pwa-badge
isSupported()
Check if the User’s browser supports the Feature,boolean
value that represents the Status of supporting.syncSetBadge(unreadCount)
Removes app’s badge Synchronously. If a valuesyncClearBadge()
or asyncClearBadge()
.syncClearBadge()
Removes app’s badge Synchronously.asyncSetBadge(unreadCount)
This API is the same as syncSetBadge()
butPromise
for error handling.asyncClearBadge()
Removes app’s badge Asynchronously and returns anPromise
for error handling.isSupported()
method function is an util for informing your users thatBrowser
or OS
and the pwa-badge
libraryset
and clear
the Badge count safely, and you can avoid usingisSupported()
before calling the set
or clear
methods.js
import PWABadge from 'pwa-badge';
// Create an Instance
const badge = new PWABadge();
if (badge.isSupported()) {
// Hoora!, Supports the Badge feature
} else {
// Does not supports
}
Sync
Set and Clear Badgejs
import PWABadge from 'pwa-badge';
// Create an Instance
const badge = new PWABadge();
// Set Badge unreadCount
badge.syncSetBadge(1);
// Clear Badge unreadCount
badge.syncClearBadge();
syncSetBadge
:
Async
Set and Clear BadgeasyncSetBadge()
and asyncClearBadge()
return empty promises
you can
use for error handling.
import PWABadge from 'pwa-badge';
// Create an Instance
const badge = new PWABadge();
// Set Badge unreadCount
badge
.asyncSetBadge(1)
.then(() => {
// Badge count has shown as well
})
.catch((e) => {
// The Browser not supporting the Badge feature or something went wrong
});
// Clear Badge unreadCount
badge
.asyncClearBadge()
.then(() => {
// Badge count has disappeared
})
.catch((e) => {
// The Browser not supporting the Badge feature or something went wrong
});
The App Badge API works on Windows, and macOS, in Chrome 81 or
later. It has also been confirmed to work on Edge 84 or later. Support for
Chrome OS is in development and will be available in a future release of
Chrome. On Android, the Badge API is not supported. Instead, Android
automatically shows a badge on app icon for the installed web app when there is
an unread notification, just as for Android apps.
Some user agents may take a number like 4000
and rewrite it as 99+
. If you
saturate the badge yourself (for example by setting it to 99
) then the +
won’t appear. No matter the actual number, just call syncSetBadge()
orasyncSetBadge()
and let the user agent deal with displaying it accordingly.
While the App Badge API in Chrome requires an installed app
as I wrote
before, you shouldn’t make calls to the Badge API dependent on the
installation state. Just call the API when it exists
and installed
on a
device, as other browsers may show the badge in other places. If it works, it
works. If not, it simply doesn’t.