有奖捉虫:行业应用 & 管理与支持文档专题 HOT

功能描述

接收消息需要接入侧监听 MESSAGE_RECEIVED 事件。

监听事件

注意
请在调用 login 接口前调用此接口监听事件,避免漏掉 SDK 派发的事件。
接口
chat.on(eventName, handler, context);
参数
名称
类型
描述
eventName
String
事件名称。所有的事件名称都存放在 TencentCloudChat.EVENT 变量中,如需要查看可以使用 console.log(TencentCloudChat.EVENT) 把所有的事件显示出来。事件列表
handler
Function
处理事件的方法,当事件触发时,会调用此 handler 进行处理。
context
* | undefined
期望 handler 执行时的上下文
返回值
示例
let onMessageReceived = function(event) {
// event.data - 存储 Message 对象的数组 - [Message]
const messageList = event.data;
messageList.forEach((message) => {
if (message.type === TencentCloudChat.TYPES.MSG_TEXT) {
// 文本消息 - https://web.sdk.qcloud.com/im/doc/v3/zh-cn/Message.html#.TextPayload
} else if (message.type === TencentCloudChat.TYPES.MSG_IMAGE) {
// 图片消息 - https://web.sdk.qcloud.com/im/doc/v3/zh-cn/Message.html#.ImagePayload
} else if (message.type === TencentCloudChat.TYPES.MSG_SOUND) {
// 音频消息 - https://web.sdk.qcloud.com/im/doc/v3/zh-cn/Message.html#.AudioPayload
} else if (message.type === TencentCloudChat.TYPES.MSG_VIDEO) {
// 视频消息 - https://web.sdk.qcloud.com/im/doc/v3/zh-cn/Message.html#.VideoPayload
} else if (message.type === TencentCloudChat.TYPES.MSG_FILE) {
// 文件消息 - https://web.sdk.qcloud.com/im/doc/v3/zh-cn/Message.html#.FilePayload
} else if (message.type === TencentCloudChat.TYPES.MSG_CUSTOM) {
// 自定义消息 - https://web.sdk.qcloud.com/im/doc/v3/zh-cn/Message.html#.CustomPayload
} else if (message.type === TencentCloudChat.TYPES.MSG_MERGER) {
// 合并消息 - https://web.sdk.qcloud.com/im/doc/v3/zh-cn/Message.html#.MergerPayload
} else if (message.type === TencentCloudChat.TYPES.MSG_LOCATION) {
// 地理位置消息 - https://web.sdk.qcloud.com/im/doc/v3/zh-cn/Message.html#.LocationPayload
} else if (message.type === TencentCloudChat.TYPES.MSG_GRP_TIP) {
// 群提示消息 - https://web.sdk.qcloud.com/im/doc/v3/zh-cn/Message.html#.GroupTipPayload
} else if (message.type === TencentCloudChat.TYPES.MSG_GRP_SYS_NOTICE) {
// 群系统通知 - https://web.sdk.qcloud.com/im/doc/v3/zh-cn/Message.html#.GroupSystemNoticePayload
const { operationType, userDefinedField } = message.payload;
// operationType - 操作类型
// userDefinedField - 用户自定义字段(对应 operationType 为 255)
// 使用 RestAPI 在群组中发送系统通知时,接入侧可从 userDefinedField 拿到自定义通知的内容。
}
});
};
chat.on(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);

取消监听事件

接口
chat.off(eventName, handler, context);
参数
名称
类型
描述
eventName
String
事件名称。所有的事件名称都存放在 TencentCloudChat.EVENT 变量中,如需要查看可以使用 console.log(TencentCloudChat.EVENT) 把所有的事件显示出来。事件列表
handler
Function
处理事件的方法,当事件触发时,会调用此 handler 进行处理。
context
* | undefined
期望 handler 执行时的上下文
返回值
示例
let onMessageReceived = function(event) {
// 收到推送的单聊、群聊、群提示、群系统通知的新消息,可通过遍历 event.data 获取消息列表数据并渲染到页面
// event.name - TencentCloudChat.EVENT.MESSAGE_RECEIVED
// event.data - 存储 Message 对象的数组 - [Message]
};
chat.off(TencentCloudChat.EVENT.MESSAGE_RECEIVED, onMessageReceived);
?


http://www.vxiaotou.com