useWebNotification

通知 API 的 Web 通知接口用於配置並向用戶顯示桌面通知。

useWebNotification 封裝了 Notifications API,用於向使用者顯示桌面通知。它回傳一個物件,包含 isSupported 旗標、permissionGranted 狀態、show 函式(顯示通知)、close 函式(關閉通知)和 ensurePermissions 函式(請求權限)。支援通知的各種選項如圖示、正文和事件回呼。

使用場景

  • 向使用者傳送即時通知(例如新訊息、任務完成、系統警報)
  • 當使用者不在應用程式分頁時提醒重要事件
  • 建構需要推送通知功能的 Web 應用程式

注意事項

  • SSR 安全:在伺服器端渲染時回傳 isSupported: false 和空操作函式。伺服器上不會建立 Notification 或請求權限。
  • 權限:通知需要明確的使用者授權。使用 ensurePermissions() 或傳入 requestPermissions: true 來提示使用者。permissionGranted ref 追蹤當前的權限狀態。
  • 相關 hooks:搭配 usePermission 使用 "notifications" 可在不觸發提示的情況下主動檢查通知權限狀態。

Usage

Live Editor

function Demo() {
  const { isSupported, show, close }
    = useWebNotification(true);
  return (
    <div>
      <p>支持狀態:{JSON.stringify(isSupported)}</p>
      {isSupported
        ? (
          <div>
            <button
              onClick={() => {
                show("你好,來自 ReactUse 的問候!");
              }}
            >
              顯示通知
            </button>
            <button onClick={close}>關閉</button>
          </div>
          )
        : (
          <div>您的瀏覽器不支持 Web 通知 API。</div>
          )}
    </div>
  );
}
Result

API

useWebNotification

Returns

UseWebNotificationReturn

Arguments

參數名描述類型預設值
requestPermissions自动请求权限boolean | undefined-

UseWebNotificationReturn

參數名描述類型預設值
isSupported浏览器是否支持boolean (必填)-
show展示函数UseWebNotificationShow (必填)-
close关闭函数() => void (必填)-
ensurePermissions请求权限函数() => Promise<boolean | undefined> (必填)-
permissionGranted权限状态React.MutableRefObject<boolean> (必填)-

UseWebNotificationShow

Returns

Notification | undefined

Arguments

參數名描述類型預設值
title通知标题string (必填)-
options通知选项NotificationOptions | undefined-