Notifications API example
Notifications API example: Notification.permission, requestPermission(), new Notification(), tag, events, and close(). Run it in the tab.
The problem
The OS will not show a message from a page that has no grant. After granted,
new Notification() is a title and a few options. The system draws it. The page only hears what
happened.
The method
requestPermission() is the prompt. The constructor needs granted.
close() removes one. The same tag replaces the previous notification instead of
stacking another. On most phones the constructor throws, and a service worker has to show it.
What to do
-
Read
Notification.permission. RunrequestPermission()if it is notgranted. -
Run
new Notification(). The message leaves the page.show,click,close, anderrorland here. - Run
close(), or run the tagged constructor again. The second one replaces the first.
Notification.permission
The current decision. default means the prompt has not been answered. No dialog.
const permission = Notification.permission
requestPermission()
Needs a user gesture and a secure context. On iOS the prompt only appears for a web app on the Home Screen. If
the result is denied, calling this again does not reopen the dialog.
const permission = await Notification.requestPermission()
permissions.query()
Same decision, through the Permissions API. prompt is this API's name for default.
change fires if the user flips it in site settings.
const status = await navigator.permissions.query({
name: "notifications",
})
status.addEventListener("change", () => {
status.state
})
new Notification()
Title, body, and an icon. The icon here is this site's favicon. The message shows outside the page. On most
mobile browsers this constructor throws. Those use ServiceWorkerRegistration.showNotification().
const notification = new Notification("Lab", {
body: "The OS can show a message.",
icon: "/favicon.svg",
})
show, click, close, error
Fired on the instance from the constructor. click focuses this tab. close also fires
when the system dismisses it. These are not the service-worker events.
notification.addEventListener("show", onShow)
notification.addEventListener("click", onClick)
notification.addEventListener("close", onClose)
notification.addEventListener("error", onError)
close()
close() removes the current notification, including from the tray. Arm listens for
visibilitychange and closes it when this tab is visible again.
notification.close()
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") notification.close()
})
tag
Same tag, new body. If a notification with lab is still up, this one replaces it. Run it twice and
edit the body between clicks.
new Notification("Lab", {
body: "The OS can show a message.",
tag: "lab",
})