useWebNotification

通知 API 的 Web 通知接口用于配置并向用户显示桌面通知。

useWebNotification 封装了 Notifications API,用于显示原生桌面/移动通知。它返回一个包含 isSupportedshow 函数(接受标题和 NotificationOptions)、close 函数、ensurePermissions 函数和 permissionGranted ref 的对象。传入 true 可在挂载时自动请求通知权限。

使用场景

  • 即使浏览器标签页未聚焦时,也向用户发送新消息、更新或事件的提醒
  • 为计划任务、定时器或日历事件发送提醒
  • 通知用户已完成的后台操作(上传、下载、构建)

注意事项

  • 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-