useWebNotification
通知 API 的 Web 通知接口用於配置並向用戶顯示桌面通知。
useWebNotification 封裝了 Notifications API,用於向使用者顯示桌面通知。它回傳一個物件,包含 isSupported 旗標、permissionGranted 狀態、show 函式(顯示通知)、close 函式(關閉通知)和 ensurePermissions 函式(請求權限)。支援通知的各種選項如圖示、正文和事件回呼。
使用場景
- 向使用者傳送即時通知(例如新訊息、任務完成、系統警報)
- 當使用者不在應用程式分頁時提醒重要事件
- 建構需要推送通知功能的 Web 應用程式
注意事項
- SSR 安全:在伺服器端渲染時回傳
isSupported: false和空操作函式。伺服器上不會建立Notification或請求權限。 - 權限:通知需要明確的使用者授權。使用
ensurePermissions()或傳入requestPermissions: true來提示使用者。permissionGrantedref 追蹤當前的權限狀態。 - 相關 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 | - |