useWebNotification
通知 API 的 Web 通知接口用于配置并向用户显示桌面通知。
useWebNotification 封装了 Notifications API,用于显示原生桌面/移动通知。它返回一个包含 isSupported、show 函数(接受标题和 NotificationOptions)、close 函数、ensurePermissions 函数和 permissionGranted ref 的对象。传入 true 可在挂载时自动请求通知权限。
使用场景
- 即使浏览器标签页未聚焦时,也向用户发送新消息、更新或事件的提醒
- 为计划任务、定时器或日历事件发送提醒
- 通知用户已完成的后台操作(上传、下载、构建)
注意事项
- 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 | - |