h5在线聊天室(附源码)

即时聊天是一个持续通信的过程,需要不断的访问数据库。因此很多人用的是websocket。

这样一来需要兼顾前端和后端以及消息的处理。比较麻烦。作为一名前端人员,不想把更多的精力花费在后端的搭建以及数据逻辑处理上,因此使用第三方提供的api就是一个很不错的选择。极光im是我无意中看懂的,花了两天时间看了下他们的api文档,写了一个简单的聊天软件。用h5封装的软件。下面让大家看一下效果

h5在线聊天室(附源码)_第1张图片

起初,我是想作为一个完整的聊天软件的,因此除了主要的聊天室,还写了登录页面,好友列表页面等,并实现了添加,删除好友等功能。这里我不多加叙述,以后有机会再和大家分享。

极光im调用api之前需要初始化,但是每次跳转页面之后它的链接就中断了。这也是我为甚么没有把软件写完的原因,因为没法。。。哎,言归正传。直接上聊天室的代码吧。


		

梦缘

05/22 06:30
流痕

你好!欢迎来到梦缘

05/22 06:30
晚亭

请文明发言

css和body主体代码没什么好说的,这个模板也是我在网上找的。你们肯定也可以找到的。

	h5{
				margin: 0;
			}
			img{
				max-width: 100%;
			    vertical-align: middle
			}
			input{
				outline: none;	
			}
			body{
			    max-width: 720px;
			    margin: 0 auto;
			    background: #f1f1f1;
			    color:#333;
			    font-size: 0.26rem;
			}
			.back{
			    position: absolute;  
				top: 0;
				left: 0.3rem;
				background:url(img/left.png) no-repeat;
			    width: 0.2rem;
			    height:0.4rem;
			    margin-top: 0.34rem;
			    background-size: 0.2rem 0.4rem;
			}
			.message{
			    background-color: #f1f1f1;
				padding: 1.2rem 0.3rem 1rem 0.3rem;	
				height: 12rem;
				overflow: auto;
			}
			.time{
			    font-size:0.24rem;
			    color:#999;
			    margin-bottom: 0.3rem;
			    text-align: center;
			}
			
			.footer{
				position: fixed;
				bottom: 0;
			    height:1rem;
			    background-color:#fff;
			    line-height:1rem;
			    width: 100%;
			    max-width: 720px;
			    border-top: 1px solid #ddd;
			}
			.footer img{
			    margin-left:0.2rem;
			    width: 0.5rem;
			}
			 .footer input{
			    margin-left:0.2rem;
			    width:4rem;
			    height:0.64rem;
			    border-radius: 0.1rem;
			    border:0.01rem solid #ddd;
			    padding : 0 0.15rem;
			
			
			}
			.footer p{
			   width:1.2rem;
			    height:0.68rem;
			    font-size:0.3rem;
			    color:#fff;
			    line-height:0.68rem;
			    text-align:center;
			    background-color:#ddd;
			    border-radius: 0.1rem;
			    float:right;
			    margin-top:0.17rem;
			    margin-right:0.2rem;
			}
			.send:after,.show:after,.msg:after{
				content: "";
				clear: both;
				display: table;	
			}
			
			.msg>img{
				width: 0.8rem;
				height: .8rem;
				border-radius: .4rem;
				float: left;
			}
			.msg>p{
				float: left;
				margin:0.5rem  0.2rem 0;
				padding: 0.25rem;
				background: #fff;
				font-size: 0.3rem;
				position: relative;
				border-radius: 0.2rem;
				max-width:5rem ;
				box-sizing: border-box;
			}
			
			.show .msg img,.show .msg p,.show .msg{
				float: right;
				position: relative;
			}
			.send,.show{
				padding-bottom: 0.3rem;
				position: relative;
			}
			.alert_novip,.flower_num,.give_flower{
				display: none;
				padding: 0.3rem 0.5rem;
				font-size: 0.28rem;
			}
			.alert_novip p,.flower_num  p{
				margin-bottom: 0.45rem;
			
			.layui-layer-wrap button{
				font-size: 0.28rem;
				padding: 0.2rem 0.3rem;
				margin-top: 0.1rem;
				background: #f8f8f8;
				border-radius: 10px;
			}
			}
			.flower_num button{
				padding: 0.2rem 0.5rem;
				border-radius: 10px;
			}
			.layui-layer-wrap button:first-child{
				float: left;
			}
			.layui-layer-wrap button:last-child{
				float: right;
				background: #FF7171;
				color: #fff;
			}
			.alert_novip button{
				padding: 0.2rem 0.3rem;
			    border-radius: 10px
			}
			.flower{
				width: 0.8rem;
				margin: 0 auto;
			}
			.give_flower{
				text-align: center;
			}
			.give_flower p{
				text-align: center;
				line-height: 1.5;
			}
			.give_flower input{
				width: 1rem;
				margin-right: 0.1rem;
				margin-top: 0.2rem;
			}
			.give_flower button{
				display: block;
				width: 3rem;
				font-size: 0.28rem;
				margin: 0 auto;
				margin-top: 0.6rem;
				float: none!important;
				line-height: 0.65rem;
				border-radius: 10px;
			}
			.mui-bar .mui-icon{padding-top: 15px;padding-bottom: 15px;color: #fff;}
			p{color: #000000;}

主要代码都是js代码,作为调用极光api和数据的处理等。http://liuqingwushui.top/api/imchat.php 是我放到自己服务器进行极光im签名鉴权的,这里发出来给你们。如果不想用可以用自己的。具体的可以查看极光api文档。

//chatroom.js

// IM初始化
 window.JIM = new JMessage({
         // debug : true
     });
 	$.ajax({
 	url:'http://liuqingwushui.top/api/imchat.php',
 	data:{},
 	success:function(data){
 	JIM.init({
 		"appkey" : data.appkey,
 		"random_str" : data.random_str,
 		"signature" : data.signature,
 		"timestamp" : data.timestamp,
 		"flag" : 0
 	}).onSuccess(function(data) {
 		console.log('success:' + JSON.stringify(data));
		ready();
 	}).onFail(function(data) {
 		console.log('error:' + JSON.stringify(data))
 		 });
 		},
 		error:function(data){
 			mui.alert("鉴权失败");
 		}
 			});

// 判断浏览器是否支持 createObjectURL api
function getObjectURL(file) {  
         var url = null;   
         if (window.createObjectURL!=undefined) {  
          url = window.createObjectURL(file) ;  
         } else if (window.URL!=undefined) { // mozilla(firefox)  
          url = window.URL.createObjectURL(file) ;  
         } else if (window.webkitURL!=undefined) { // webkit or chrome  
          url = window.webkitURL.createObjectURL(file) ;  
         }  
         return url ;  
}

function ready(){
	(function (doc, win) {
	        var docEl = doc.documentElement,
	            resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
	            recalc = function () {
	                var clientWidth = docEl.clientWidth;
	                if (!clientWidth) return;
	                if(clientWidth>=720){
	                    docEl.style.fontSize = '100px';
	                }else{
	                    docEl.style.fontSize = 100 * (clientWidth / 720) + 'px';
	                }
	            };
	
	        if (!doc.addEventListener) return;
	        win.addEventListener(resizeEvt, recalc, false);
	        doc.addEventListener('DOMContentLoaded', recalc, false);
	    })(document, window);
		
	/*发送消恿*/
	function send(headSrc,str,name){
		var html="
"+name+""+ "

"+str+"

"; upView(html); } /*接受消息*/ function show(headSrc,str,name){ var html="
"+name+""+ "

"+str+"

"; upView(html); } /*更新视图*/ function upView(html){ $('.message').append(html); // $('body').animate({scrollTop:$('.message').outerHeight()-window.innerHeight},200); var ele = document.getElementById('message'); ele.scrollTop = ele.scrollHeight; } function sj(){ return parseInt(Math.random()*10) } $(function(){ $("input[type='file']").change(function(){ var file=this.files[0]; if(!file.length){ //获取用户信息 var name=""; JIM.getUserInfo({ 'username' : user }).onSuccess(function(data) { name=data.user_info; }).onFail(function(data) { console.log(data); }); var fd = new FormData(); fd.append("avatar",file); // 发送消息 JIM.sendChatroomPic({ 'target_rid' : "23638768", 'image' : fd, }).onSuccess(function(data,msg) { console.log(msg); JIM.getResource({ 'media_id' : name.avatar, }).onSuccess(function(src) { var s = getObjectURL(file);show(src.url,"",name.nickname);}) }).onFail(function(data) { //同发送单聊文本 }); } }) $('.footer').on('keyup','input',function(){ if($(this).val().length>0){ $(this).next().css('background','#114F8E'); }else{ $(this).next().css('background','#ddd'); } }) $('.footer p').click(function(){ //获取用户信息 var name=""; JIM.getUserInfo({ 'username' : user }).onSuccess(function(data) { name=data.user_info; }).onFail(function(data) { console.log(data); }); var that=this; JIM.sendChatroomMsg({ 'target_rid' : "23638768", 'content' : $(that).prev().val() }).onSuccess(function(data,msg) { var con=$(that).prev().val(); if(name.avatar!=""){ JIM.getResource({ 'media_id' : name.avatar, }).onSuccess(function(src) {show(src.url,con,name.nickname);}) } else{show("img/touxiang.png",con,name.nickname);} $("#text").val(""); }).onFail(function(data) { console.log('error:' + JSON.stringify(data)); }); }) }) /*测试数据*/ // var arr=['我是小Q','好久没联系了_','你在想我乿','怎么不和我说诿','跟我聊会天吧']; // var imgarr=['img/touxiang.png','img/touxiangm.png'] // test() // function test(){ // $(arr).each(function(i){ // setTimeout(function(){ // send("img/touxiang.png",arr[i]) // },sj()*500) // }) // } var user= localStorage.getItem("account"); var pass= localStorage.getItem("pass"); JIM.login({ 'username' : user, 'password': pass }).onSuccess(function(data) { console.log(data); localStorage.setItem("account", data.username); //业务事件监听 JIM.onEventNotification(function(data) { console.log('event_receive: ' + JSON.stringify(data)); }); //用户信息变更监听 JIM.onUserInfUpdate(function(data) { console.log('onUserInfUpdate : ' + JSON.stringify(data)); }); //业务事件同步监听 JIM.onSyncEvent(function(data) { console.log('onSyncEvent : ' + JSON.stringify(data)); }); //消息已读数变更事件实时监听 JIM.onMsgReceiptChange(function(data){ console.log('onMsgReceiptChange : ' + JSON.stringify(data)); }); //消息已读数变更事件同步监听 JIM.onSyncMsgReceipt(function(data){ console.log('onSyncMsgReceipt : ' + JSON.stringify(data)); }); //会话未读数变更监听(多端在线) JIM.onMutiUnreadMsgUpdate(function(data){ console.log('onConversationUpdate : ' + JSON.stringify(data)); }); //消息透传监听 JIM.onTransMsgRec(function(data){ console.log('onTransMsgRec : ' + JSON.stringify(data)); }); //聊天室消息监听 JIM.onRoomMsg (function(data){ console.log(data); var data=data; JIM.getUserInfo({ 'username' : data.content.from_id, }).onSuccess(function(d) { //data.user_info.avatar 头像 JIM.getResource({ 'media_id' : d.user_info.avatar, }).onSuccess(function(src) { if(data.content.msg_type=="text"){ send(src.url,data.content.msg_body.text,data.content.from_name); } if(data.content.msg_type=="image"){ from_name=data.content.from_name; JIM.getResource({ 'media_id' : data.content.msg_body.media_id, }).onSuccess(function(img) { //data.code 返回码 //data.message 描述 //data.url 资源临时访问路径,具体超时时间expire time会包含在url中 send(src.url,"",d.user_info.nickname); console.log(data); }).onFail(function(data) { }); } }).onFail(function(e) { if(data.content.msg_type=="text"){ send("img/touxiang.png",data.content.msg_body.text,data.content.from_name); } if(data.content.msg_type=="image"){ from_name=data.content.from_name; JIM.getResource({ 'media_id' : data.content.msg_body.media_id, }).onSuccess(function(img) { //data.code 返回码 //data.message 描述 //data.url 资源临时访问路径,具体超时时间expire time会包含在url中 send("img/touxiang.png","",d.user_info.nickname); console.log(data); }).onFail(function(data) { }); } }) }) // if(data.content.msg_type=="text"){ // send("litpic",data.content.msg_body.text,data.content.from_name); // } // if(data.content.msg_type=="image"){ // from_name=data.content.from_name; // JIM.getResource({ // 'media_id' : data.content.msg_body.media_id, // }).onSuccess(function(data) { // //data.code 返回码 // //data.message 描述 // //data.url 资源临时访问路径,具体超时时间expire time会包含在url中 // send("litpic","",from_name); // console.log(data); // }).onFail(function(data) { // //data.code 返回码 // //data.message 描述 // console.log(data); // }); // } }); //加入聊天室 JIM.enterChatroom({'id':"23638768"}).onSuccess(function(data) { console.log('success:' + JSON.stringify(data)); }).onFail(function(data) { }); }).onFail(function(data) { mui.openWindow({url:'login.html'}) }).onTimeout(function(data) { mui.openWindow({url:'login.html'}) }); }

都是一些很基础的代码,技术含量不是很高。也欢迎大家一次探讨。有不懂的可以评论留言,我看到了会给你们一一解答。

2022年11月23日补充

极光IM文档好像更新了,所以代码要改一下。本着帮人帮到底的原则。特意将代码完善了一下并开源出来。下载地址:H5聊天源码(完整版)-Javascript文档类资源-CSDN下载

转载请注明出处,谢谢。

你可能感兴趣的:(js,H5,聊天,极光,聊天室,在线聊天)