guarahooks's logo

guarahooks

Command Palette

Search for a command to run...

useNotifications

A React hook for managing browser notifications with comprehensive feature detection and fallback support

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

Default

Installation

Props

The hook returns an object with the following properties:

PropertyTypeDescription
permission'default' | 'granted' | 'denied'Current notification permission status
isSupportedbooleanWhether the browser supports the Notifications API
isSecureContextbooleanWhether the current context is secure (HTTPS)
supportsActionsbooleanWhether the browser supports notification actions
supportsBadgebooleanWhether the browser supports notification badges
supportsImagebooleanWhether the browser supports notification images
supportsVibratebooleanWhether the browser supports notification vibration
supportsSoundbooleanWhether the browser supports notification sounds
requestPermission() => Promise<NotificationPermission>Function to request notification permission
showNotification(title: string, options?: NotificationOptions) => voidFunction to show a notification

Options

The showNotification function accepts an optional options parameter:

PropertyTypeDescription
bodystringThe body text of the notification
iconstringThe URL of an icon to display in the notification
imagestringThe URL of an image to display in the notification
badgestringThe URL of an image used to represent the notification when there is not enough space
tagstringAn ID for a given notification that allows you to find, replace, or remove the notification
dataunknownArbitrary data that you want to associate with the notification
requireInteractionbooleanWhether the notification should remain active until the user clicks or dismisses it
silentbooleanWhether the notification should be silent
soundstringThe URL of an audio file to play with the notification
vibratenumber | number[]A vibration pattern for devices with vibration hardware
dir'auto' | 'ltr' | 'rtl'The direction of the notification's text
langstringThe notification's language
renotifybooleanWhether the user should be notified after a new notification replaces an old one
stickybooleanWhether the notification should be sticky
timestampnumberThe time at which the notification was created
actionsArray<{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

  1. Always check for browser support before using the hook
  2. Request permission only after a user interaction
  3. Provide clear feedback about the notification permission status
  4. Implement fallback UI notifications for unsupported browsers
  5. Use appropriate icons and badges to improve notification visibility
  6. Consider the user's context when showing notifications
  7. Handle notification errors gracefully
  8. 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

  1. Real-time Updates: Notify users of new messages or events
  2. Background Tasks: Alert users when long-running tasks complete
  3. System Alerts: Inform users about system status or errors
  4. User Engagement: Remind users about important actions or deadlines
  5. Multi-tab Coordination: Synchronize state across multiple tabs