求助:基于Sendbird与Cordova的聊天应用实现推送通知方案
我刚帮几个做Cordova+Sendbird聊天应用的开发者解决过类似的推送问题,确实Sendbird的JavaScript SDK目前没有内置推送通知能力——官方的设计逻辑应该是考虑到JS端(尤其是Cordova这种跨平台容器)的推送依赖原生层能力,所以更推荐结合原生推送服务(比如FCM)来实现,下面给你一步步拆解可行的方案:
1. 先搞定Cordova的FCM环境配置
首先得在你的Cordova项目里集成靠谱的FCM插件,我个人推荐cordova-plugin-fcm-with-dependecy-updated,这个插件维护得比较好,兼容新版FCM,安装命令:
cordova plugin add cordova-plugin-fcm-with-dependecy-updated
然后去Firebase控制台创建项目,下载Android的google-services.json和iOS的GoogleService-Info.plist,分别放到Cordova项目的platforms/android/app/和platforms/ios/目录下(注意每次重新添加平台后可能需要重新放置这两个文件)。
2. 把FCM设备令牌同步到Sendbird
当应用启动后,先获取FCM的设备令牌,然后把这个令牌绑定到当前登录的Sendbird用户身上——这样Sendbird后台才知道要给哪个设备推送消息:
document.addEventListener('deviceready', function() { // 获取FCM令牌 FCM.getToken().then(token => { console.log('拿到FCM令牌:', token); // 连接Sendbird并注册令牌 const sb = new SendBird({ appId: '你的Sendbird应用ID' }); sb.connect('当前用户ID', '用户AccessToken(可选)', (user, error) => { if (error) return console.error('连接Sendbird失败:', error); // 注册令牌到Sendbird,第三个参数区分平台:'gcm'对应Android,'apns'对应iOS sb.registerPushTokenForCurrentUser(token, (response, error) => { if (error) console.error('注册令牌失败:', error); else console.log('令牌绑定成功:', response); }, 'gcm'); }); }).catch(err => console.error('获取FCM令牌失败:', err)); });
这里建议把用户的FCM令牌同时存在你的服务器数据库里,后面用webhook方案时会用到。
3. 两种触发推送的方式(选一种就行)
方式一:客户端本地监听Sendbird事件触发推送
适合简单场景,当应用在前台时可以直接弹通知,后台时依赖FCM的后台推送能力:
// 给Sendbird添加消息监听 sb.addChannelHandler('唯一标识的HandlerID', new SendBird.ChannelHandler({ onMessageReceived: (channel, message) => { // 判断应用是否在后台 let isAppInBackground = false; document.addEventListener('pause', () => isAppInBackground = true); document.addEventListener('resume', () => isAppInBackground = false); if (isAppInBackground) { // 调用FCM显示本地通知 FCM.presentLocalNotification({ title: `来自${message.sender.nickname}的消息`, body: message.message, sound: 'default', click_action: 'FCM_PLUGIN_ACTIVITY', icon: 'notification_icon' // 记得在资源文件夹里放这个图标 }); } } }));
方式二:Sendbird Webhook + FCM Server API(更推荐)
如果你的应用需要在后台甚至被杀死时也能收到推送,这个方案更可靠——由Sendbird后台触发webhook,你的服务器调用FCM API发送推送:
- 登录Sendbird控制台,进入你的应用,找到Settings > Webhooks,添加一个新的webhook,选择Message sent事件。
- 写一个简单的后端接口(比如用Node.js),接收Sendbird的webhook请求,然后调用FCM的Server API发推送:
const express = require('express'); const axios = require('axios'); const app = express(); app.use(express.json()); // 接收Sendbird的webhook请求 app.post('/sendbird-webhook', async (req, res) => { const message = req.body.message; const recipientUserId = message.recipient_id; // 单聊拿这个,如果是群聊就从channel成员里取目标用户 // 从你的数据库里取出该用户的FCM令牌 const fcmToken = await yourDatabase.query(`SELECT fcm_token FROM users WHERE id = ?`, [recipientUserId]); // 调用FCM API发送推送 await axios.post('https://fcm.googleapis.com/fcm/send', { to: fcmToken, notification: { title: `来自${message.sender.nickname}的消息`, body: message.message, sound: 'default' }, data: { channelUrl: message.channel_url, messageId: message.message_id } }, { headers: { 'Authorization': 'key=你的FCM服务器密钥', 'Content-Type': 'application/json' } }); res.sendStatus(200); // 给Sendbird返回成功状态 }); app.listen(3000, () => console.log('Webhook服务启动啦!'));
- 把这个后端接口的URL填到Sendbird的webhook设置里,保存就ok了。
4. 处理通知点击事件
当用户点击推送通知时,需要跳转到对应的聊天界面,在Cordova里可以监听FCM的通知点击事件:
FCM.onNotification().subscribe(data => { if (data.wasTapped) { // 通知是在后台被点击的,跳转到对应聊天频道 const channelUrl = data.channelUrl; // 这里写你的页面跳转逻辑,比如打开聊天页面并传入channelUrl参数 console.log('用户点击了通知,准备跳转频道:', channelUrl); } else { // 通知是在前台收到的,可以做弹窗提示或者直接跳转到聊天界面 console.log('前台收到新消息通知:', data); } });
几个重要的注意事项
- 确保Sendbird的用户ID和你应用里的用户ID完全一致,不然令牌绑定会出错。
- iOS平台需要在
config.xml里配置推送权限:
<platform name="ios"> <config-file parent="NSRemoteNotificationUsageDescription" platform="ios" target="*-Info.plist"> <string>接收聊天消息通知,不错过好友消息</string> </config-file> </platform>
- Android平台要确保
AndroidManifest.xml里的FCM配置正确,一般插件会自动处理,但如果有问题可以手动检查一下权限和服务配置。
内容的提问来源于stack exchange,提问作者sqwale

