GooseUI

Components

useNotificationPermission

New

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

npx shadcn@latest add @gooseui/use-notification-permission
pnpm dlx shadcn@latest add @gooseui/use-notification-permission
yarn dlx shadcn@latest add @gooseui/use-notification-permission
bunx --bun shadcn@latest add @gooseui/use-notification-permission

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

NameTypeDefaultDescription
dismissDaysnumber7Days to stay quiet after a dismissal
storageKeystring"notification-prompt-dismissed-at"localStorage key for the dismissal time

Returns

NameTypeDescription
permission"default" | "granted" | "denied" | "unsupported""default", "granted", "denied", or "unsupported" without the Notification API and on the server
isSupportedbooleanThe browser has the Notification API
isDismissedbooleanThe user dismissed the offer less than dismissDays ago
shouldOfferbooleanThe permission is undecided and the user has not dismissed
request() => Promise<NotificationPermissionState>Opens the browser dialog and resolves to the resulting permission
dismiss() => voidSaves the dismissal time and hides the offer
resetDismiss() => voidForgets 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”.