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

如何在Capacitor聊天应用中结合WebSocket实现推送通知

问题描述

我找不到结合WebSocket实现推送通知的正确方案。我的需求很简单,就像WhatsApp聊天一样,收到消息时以推送通知的形式展示内容。这是推送通知的官方文档。

现有代码
/**
 *  推送通知相关代码
*/

import { PushNotifications } from '@capacitor/push-notifications';

const addListeners = async () => {
  await PushNotifications.addListener('registration', token => {
    console.info('注册令牌: ', token.value);
  });

  await PushNotifications.addListener('registrationError', err => {
    console.error('注册错误: ', err.error);
  });

  await PushNotifications.addListener('pushNotificationReceived', notification => {
    console.log('收到推送通知: ', notification);
  });

  await PushNotifications.addListener('pushNotificationActionPerformed', notification => {
    console.log('推送通知操作已执行', notification.actionId, notification.inputValue);
  });
}

const registerNotifications = async () => {
  let permStatus = await PushNotifications.checkPermissions();

  if (permStatus.receive === 'prompt') {
    permStatus = await PushNotifications.requestPermissions();
  }

  if (permStatus.receive !== 'granted') {
    throw new Error('用户拒绝了权限!');
  }

  await PushNotifications.register();
}

const getDeliveredNotifications = async () => {
  const notificationList = await PushNotifications.getDeliveredNotifications();
  console.log('已送达的通知', notificationList);

/**
   WebSocket相关代码
*/

// 创建WebSocket连接。
const socket = new WebSocket("ws://localhost:8080");

// 连接已打开
socket.addEventListener("open", (event) => {
  socket.send("你好,服务器!");
});

// 监听消息
socket.addEventListener("message", (event) => {
  console.log("来自服务器的消息 ", event.data);
  PushNotifications.send("来自服务器的消息 ", event.data);  // 测试用,但不生效
});

}
核心问题

你代码里的PushNotifications.send()是错误用法——Capacitor的PushNotifications API没有这个方法,这是导致功能失效的直接原因。

正确实现方案

要实现类似WhatsApp的即时通知,需要区分前台在线和后台/离线两种场景:

1. 前台在线:WebSocket消息触发本地通知

当应用在前台运行时,WebSocket收到消息后,用Capacitor的LocalNotifications API主动弹出系统通知。

步骤1:安装本地通知依赖

npm install @capacitor/local-notifications
npx cap sync

步骤2:修正代码逻辑

替换原WebSocket消息监听的错误调用,改用LocalNotifications.schedule():

import { PushNotifications } from '@capacitor/push-notifications';
import { LocalNotifications } from '@capacitor/local-notifications';

// 保留原有addListeners、registerNotifications函数不变

const initWebSocket = async () => {
  // 创建WebSocket连接
  const socket = new WebSocket("ws://localhost:8080");

  socket.addEventListener("open", (event) => {
    socket.send("你好,服务器!");
  });

  socket.addEventListener("message", async (event) => {
    console.log("来自服务器的消息 ", event.data);
    
    // 检查并申请本地通知权限
    let permStatus = await LocalNotifications.checkPermissions();
    if (permStatus.display === 'prompt') {
      permStatus = await LocalNotifications.requestPermissions();
    }

    // 权限通过则触发本地通知
    if (permStatus.display === 'granted') {
      await LocalNotifications.schedule({
        notifications: [
          {
            title: "新消息",
            body: event.data,
            id: Date.now(), // 生成唯一ID避免重复
            schedule: { at: new Date(Date.now() + 100) }, // 立即触发
            sound: "default" // 使用系统默认提示音
          }
        ]
      });
    }
  });
}

// 应用初始化时执行所有启动逻辑
const initApp = async () => {
  await addListeners();
  await registerNotifications();
  initWebSocket();
}

initApp();

2. 后台/离线:依赖FCM/APNs远程推送

当应用在后台或离线时,WebSocket无法保持连接,此时需要服务器通过Firebase Cloud Messaging(安卓)或Apple Push Notification service(iOS)发送远程推送,客户端通过之前注册的令牌接收,pushNotificationReceived监听器会自动触发系统通知。

完整流程说明

  • 应用启动时,先完成推送权限申请和注册,确保能接收远程推送。
  • 建立WebSocket连接,实时监听服务器消息。
  • 前台收到消息时,用本地通知API弹出即时提醒;后台/离线时,由服务器通过官方推送服务发送通知。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:46:32