useNotifications
This component demonstrates the use of the
useNotifications
hook to manage browser notifications.Browser Support
Not SupportedNot Secure
Feature Support
Actions ✗Badge ✗Image ✗Vibrate ✗Sound ✗
Permission Status
DefaultNot Supported
Your browser does not support the Notifications API. Consider using a fallback UI notification system.
Not Secure
The Notifications API requires a secure context (HTTPS). Please use HTTPS to enable notifications.
Installation
Props
The hook returns an object with the following properties:
Property | Type | Description |
---|---|---|
permission | 'default' | 'granted' | 'denied' | Current notification permission status |
isSupported | boolean | Whether the browser supports the Notifications API |
isSecureContext | boolean | Whether the current context is secure (HTTPS) |
supportsActions | boolean | Whether the browser supports notification actions |
supportsBadge | boolean | Whether the browser supports notification badges |
supportsImage | boolean | Whether the browser supports notification images |
supportsVibrate | boolean | Whether the browser supports notification vibration |
supportsSound | boolean | Whether the browser supports notification sounds |
requestPermission | () => Promise<NotificationPermission> | Function to request notification permission |
showNotification | (title: string, options?: NotificationOptions) => void | Function to show a notification |
Options
The showNotification
function accepts an optional options
parameter:
Property | Type | Description |
---|---|---|
body | string | The body text of the notification |
icon | string | The URL of an icon to display in the notification |
image | string | The URL of an image to display in the notification |
badge | string | The URL of an image used to represent the notification when there is not enough space |
tag | string | An ID for a given notification that allows you to find, replace, or remove the notification |
data | unknown | Arbitrary data that you want to associate with the notification |
requireInteraction | boolean | Whether the notification should remain active until the user clicks or dismisses it |
silent | boolean | Whether the notification should be silent |
sound | string | The URL of an audio file to play with the notification |
vibrate | number | number[] | A vibration pattern for devices with vibration hardware |
dir | 'auto' | 'ltr' | 'rtl' | The direction of the notification's text |
lang | string | The notification's language |
renotify | boolean | Whether the user should be notified after a new notification replaces an old one |
sticky | boolean | Whether the notification should be sticky |
timestamp | number | The time at which the notification was created |
actions | Array<{action: string, title: string, icon?: string}> | Actions to display in the notification |
Key Features & Details
Browser Support
The Notifications API is supported in most modern browsers with varying feature support:
- Chrome: Full support
- Firefox: Full support
- Safari: Partial support (some features may not be available)
- Edge: Full support
- Opera: Full support
Note: The API requires a secure context (HTTPS) to work, except for localhost.
Feature Detection
- The hook automatically detects browser support for various notification features
- Provides boolean flags for each supported feature
- Handles cases where certain features might not be available
- Gracefully degrades functionality based on browser capabilities
Permission Management
- Tracks the current permission status
- Provides a function to request permission
- Handles permission changes across browser tabs
- Manages permission state persistence
Best Practices & Caveats
- Always check for browser support before using the hook
- Request permission only after a user interaction
- Provide clear feedback about the notification permission status
- Implement fallback UI notifications for unsupported browsers
- Use appropriate icons and badges to improve notification visibility
- Consider the user's context when showing notifications
- Handle notification errors gracefully
- Clean up notifications when they're no longer needed
Examples
Basic Usage
const { permission, requestPermission, showNotification } = useNotifications();
const handleShowNotification = () => {
showNotification('New Message', {
body: 'You have a new message from John',
icon: '/path/to/icon.png',
});
};
With Feature Detection
const { isSupported, supportsActions, supportsBadge, showNotification } =
useNotifications();
const handleShowNotification = () => {
showNotification('New Message', {
body: 'You have a new message from John',
icon: '/path/to/icon.png',
badge: supportsBadge ? '/path/to/badge.png' : undefined,
actions: supportsActions
? [
{
action: 'view',
title: 'View Message',
},
]
: undefined,
});
};
With Permission Management
const { permission, requestPermission } = useNotifications();
const handleRequestPermission = async () => {
try {
await requestPermission();
} catch (error) {
console.error('Failed to request permission:', error);
}
};
Common Use Cases
- Real-time Updates: Notify users of new messages or events
- Background Tasks: Alert users when long-running tasks complete
- System Alerts: Inform users about system status or errors
- User Engagement: Remind users about important actions or deadlines
- Multi-tab Coordination: Synchronize state across multiple tabs