useNotificationPermission reads the browser's notification permission, keeps it in sync when the user changes it in the site settings, and remembers when the user said no. Build your own offer on top of it, or use the ready Notification Prompt banner.
Preview
- permission
- unsupported
- isSupported
- false
- isDismissed
- false
- shouldOffer
- false
Permission is read from the browser. If you already answered, change it in the site settings to try again.
Installation
Usage
import { Button } from "@/components/ui/button"
import { useNotificationPermission } from "@/hooks/use-notification-permission"
export function EnableNotifications() {
const { shouldOffer, request } = useNotificationPermission()
if (!shouldOffer) return null
return (
<Button type="button" onClick={() => request()}>
Turn on notifications
</Button>
)
}Examples
Your own button
Call request() from a click. The promise resolves to the final permission, or to “unsupported” where the browser has no Notification API.
const { request } = useNotificationPermission()
async function enable() {
const permission = await request()
if (permission === "granted") {
new Notification("Notifications are on")
}
}Quiet period
After dismiss() the hook keeps shouldOffer false for dismissDays. Blocking the browser dialog does not count as a dismissal, the permission is simply “denied”.
// ask again in a month
const notifications = useNotificationPermission({
dismissDays: 30,
storageKey: "my-app:notifications-dismissed",
})Parameters
| Name | Type | Default | Description |
|---|---|---|---|
| dismissDays | number | 7 | Days to stay quiet after a dismissal |
| storageKey | string | "notification-prompt-dismissed-at" | localStorage key for the dismissal time |
Returns
| Name | Type | Description |
|---|---|---|
| permission | "default" | "granted" | "denied" | "unsupported" | "default", "granted", "denied", or "unsupported" without the Notification API and on the server |
| isSupported | boolean | The browser has the Notification API |
| isDismissed | boolean | The user dismissed the offer less than dismissDays ago |
| shouldOffer | boolean | The permission is undecided and the user has not dismissed |
| request | () => Promise<NotificationPermissionState> | Opens the browser dialog and resolves to the resulting permission |
| dismiss | () => void | Saves the dismissal time and hides the offer |
| resetDismiss | () => void | Forgets the dismissal |
Notes
- request() works only from a click or another user action. Browsers ignore or block it otherwise.
- Once the permission is “denied”, the page cannot ask again. The user has to change it in the site settings.
- iPhone Safari has the Notification API only for a site added to the home screen. Elsewhere permission is “unsupported”.