You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React JS PWA添加带操作按钮的原生通知问题咨询(新手)

在React PWA中实现带操作按钮的原生通知

1. 先获取用户通知权限

原生浏览器通知需要用户主动授权,在React组件里可通过以下代码请求权限:

const requestNotificationPermission = async () => {
  const permission = await Notification.requestPermission();
  if (permission === 'granted') {
    console.log('通知权限已授予');
  } else {
    console.log('用户拒绝了通知权限');
  }
};

// 可在组件挂载或按钮点击时触发权限请求
useEffect(() => {
  requestNotificationPermission();
}, []);

2. 确保Service Worker正常运行

PWA原生通知依赖Service Worker处理后台事件,若用Create React App创建项目:

  • 生产环境默认启用Service Worker;
  • 开发环境需在src/index.js中把serviceWorkerRegistration.unregister()改为serviceWorkerRegistration.register()。

之后要在Service Worker文件(如src/service-worker.js或CRA生成的public/service-worker.js)中监听通知相关事件。

3. 发送带操作按钮的通知

权限和Service Worker就绪后,即可发送带操作按钮的通知,在React组件中编写如下代码:

const sendNotification = async () => {
  const registration = await navigator.serviceWorker.ready;
  await registration.showNotification('新消息提醒', {
    body: '你有一条待处理的请求',
    icon: '/icons/icon-192x192.png', // 替换为你的PWA图标路径
    actions: [
      {
        action: 'approve',
        title: '批准',
        icon: '/icons/approve-icon.png' // 可选,按钮图标
      },
      {
        action: 'reject',
        title: '拒绝',
        icon: '/icons/reject-icon.png'
      }
    ],
    requireInteraction: true // 让通知保持显示,直到用户操作
  });
};

4. 处理通知操作事件

在Service Worker文件中监听notificationclick事件,根据用户点击的按钮执行对应逻辑:

self.addEventListener('notificationclick', (event) => {
  event.notification.close();

  switch (event.action) {
    case 'approve':
      console.log('用户点击了批准按钮');
      clients.openWindow('/approve-page'); // 打开对应页面
      break;
    case 'reject':
      console.log('用户点击了拒绝按钮');
      clients.openWindow('/reject-page');
      break;
    default:
      // 用户点击通知主体而非操作按钮时的逻辑
      clients.openWindow('/');
      break;
  }
});

注意事项

  • 测试需用localhost或HTTPS环境,浏览器仅在安全环境下支持Service Worker和通知API;
  • 不同浏览器对通知样式、操作按钮的支持有差异,部分移动端浏览器可能隐藏图标或限制按钮数量;
  • 若需服务器推送后台通知,可结合Web Push API,这需要额外的后端配置。

内容的提问来源于stack exchange,提问作者Radhika Padiya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 11:22:20