web项目中使用iframe的方式引入腾讯IM即时通信,应用场景
最近公司有项目需要客服聊天功能,我们选择了腾讯的IM,对于前端来说很好控制,前端只需对应传参即可,大多由后端控制。百度了很多都没找到想要的教程,所以自己写下来对于引用IM的实践。
功能:
1. 一对一聊天
2.群组聊天
3.默认选中对话
4.以及自带的发送表情包、文件、图片、消息撤回、多选转发等类似于QQ的功能
官方demo下载地址:https://github.com/tencentyun/TIMSDK/tree/master/H5
官方SDK文档:https://web.sdk.qcloud.com/im/doc/zh-cn/SDK.html#login
项目结构见Gitee地址:https://gitee.com/jiangxingjie/tengxun-chat.git
一、下载IM并配置 SDKAppID
和 SECRETKEY
,IM是vue写的,所以大部分地方可以去自己看明白更改。
二、默认选中对话,所有的聊天对话都为后端生成,前端有一对多的情况,所以我们通过后端传值的方式拿到要激活的会话默认选中。默认选中调用vuex里的checkoutConversation方法。
注意:一定要isSDKReady,也就是初始化成功之后再去调checkoutConversation方法,不然会因为未初始化报错。
onReadyStateUpdate({ name }) {
const isSDKReady = name === this.TIM.EVENT.SDK_READY ? true : false;
this.$store.commit("toggleIsSDKReady", isSDKReady);
if (isSDKReady) {
this.tim
.getMyProfile()
.then(({ data }) => {
this.$store.commit("updateCurrentUserProfile", data);
})
.catch((error) => {
this.$store.commit("showMessage", {
type: "error",
message: error.message,
});
});
this.$store.dispatch("getBlacklist");
// 登录trtc calling
this.trtcCalling.login({
sdkAppID: this.sdkAppID,
userID: this.userID,
userSig: this.userSig,
});
// 默认选中要沟通的群
// console.log(this.groupID, '这是默认选中要沟通的群')
this.$store.dispatch(
"checkoutConversation",
this.groupID //名片ID
);
}
},
三、用iframe引入项目
HTML部分
<!-- iframedialog -->
<base-dialog class="dialog-IM" width="1000px" :visible.sync="TimShow" height="800px">
<iframe :src="TimSrc" height="100%" width="100%"></iframe>
</base-dialog>
唤起IMdialog
async toTIM(groupId){
const res = await imMsgClear()
if(res.success){
this.ImMessage = 0
this.TimSrc=process.env.IM_URL+'userId='+this.userInfo.id+'&userSig='+this.userInfo.imSign+'&groupId='+groupId
this.TimShow = true
}
}
因为同一id不能多处登录IM,所以每次关掉dialog都要调用一遍IM的退出api,我们将IM项目给父页面传值
在IM项目中调用vuex里的logout方法,给这个方法添加上iframe给父页面传值
logout(context) {
// 若有当前会话,在退出登录时已读上报
if (context.rootState.conversation.currentConversation.conversationID) {
tim.setMessageRead({ conversationID: context.rootState.conversation.currentConversation.conversationID })
}
tim.logout().then(() => {
window.parent.postMessage('logout',"*");
context.commit('toggleIsLogin')
context.commit('stopComputeCurrent')
context.commit('reset')
})
}
父页面接受值
mounted() {
let that = this;
//接受iframe页面的值
window.addEventListener("message", function (e) {
// console.log(e.data)
if(e.data=='logout'){
that.TimSrc = ''
that.TimShow = false
}
});
}
腾讯IM官方给的是vue项目,熟悉vue的人改起来应该还是挺方便的。
2021-07-12新增router,取参数更加方便。