javascript - 使用 Firebase 数据库 JavaScript 在 Web 应用程序上进行即时聊天

标签 javascript jquery firebase web

在我的网站上,我正在使用 Firebase 数据库创建一个即时消息服务。我已获得聊天功能,因此用户可以向聊天发送消息,该消息将显示在显示框中。

我遇到的问题是,当创建新聊天并且用户开始对话时,消息会按照他们正在进行的对话的顺序显示,如下所示:

enter image description here

但是当页面刷新并从数据库中提取消息时,显示如下。

enter image description here

我的聊天数据库结构如下:

enter image description here

我的聊天 JS 代码是:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
	var db = firebase.database();
	var currentProperty = localStorage.getItem("prop");
	
	db.ref('addresses/'+currentProperty+'/chat/group').on("child_added", function(data){
		//Set Local Variables
		var message = data.child("message").val();
		var date = data.child("date").val();
		var sender = data.child("uid").val();
		var time = data.child("time").val();
		var who;
		var getCurrentDate = new Date;
		day = getCurrentDate.getDate();
		month = getCurrentDate.getMonth() + 1;										
		year = getCurrentDate.getFullYear();
		var newDate = [day, month, year].join('/');
		var title = document.getElementById("chatTitle");
		db.ref('addresses/'+currentProperty+'/firstLine').once("value", function(snapshot){
			title.innerHTML = "<i class='fas fa-home' style='font-size:150%;margin-right:10px'></i>Group chat with all persons involved with " + capitalLetter(snapshot.val());
		});
		
		if(sender == user.uid){who = 'boxCurrent currentUser';}
		else
		{who = 'boxOther otherUser';}
		
		if(date == newDate){date = 'Today'}
		
		db.ref('users/'+sender+'/firstName').on('value', function(data){
			var name = data.val();
			if(who == 'boxCurrent currentUser'){
				var messageD = "<div id='userMessageDisplay' style='width:100%;text-align:end;'><span class='message-data-time'>"+time+",  "+date+"    </span><span id='userName'>"+name+"</span><div id='hello' class='"+who+"' style= height:100%;'>"+message+"</div></div>";
			$('#displayBox').append(messageD);
			}
			else{
				var messageD = "<div id='userMessageDisplay' style='width:100%;'><span class='message-name'>"+name+"</span><span class='message-data-time'>    "+time+",  "+date+"</span><div id='hello' class='"+who+"' style='width:70%; height:100%;'>"+message+"</div></div>";
			$('#displayBox').append(messageD);
			}
		});
	});
	
	db.ref('addresses/'+currentProperty+'/tenant').orderByKey().once("value", function(snapshot){
		snapshot.forEach(function(child){
		  var key = child.key;
		  console.log(key);
		  db.ref('users/'+key+'/firstName').once("value", function(data){
			  var first = data.val();
			  var appendFirst = "<li style='padding: 5px 10px 0 10px; height:75px;'><i class='fas fa-user-circle' style='font-size:400%; float:left;color:#6a6c75;'></i><div class='about' style='height:100%;padding: 10px 0 0 70px;'><div id='append2"+key+"' class='profileName' style='color:#fff;'>"+first;
			  $('#peopleList').append(appendFirst);

		  });
		  db.ref('users/'+key+'/lastName').once("value", function(data){
			  var last = data.val();
			  var appendLast = " "+last+"</div>"
			  $('#append2'+key).append(appendLast);
		  });
		  db.ref('users/'+key+'/onlineStatus').once("value", function(data){
			  var onlineStatus = data.val();
			  console.log(onlineStatus);
			  if(onlineStatus == 'Online'){
			  var appendStatus = "<div class='status' style='color:#a8aac3;'><i class='fa fa-circle' online style='color:#86BB71; margin-right:10px;font-size:80%;border:1px solid #fff;border-radius:50%;'></i>Online</div></div></li>"
			  $('#append2'+key).append(appendStatus);
			  }
			  else{
				  appendStatus = "<div class='status' style='color:#a8aac3;'><i class='fa fa-circle offline' style='color:#E38968;margin-right:10px;font-size:80%;border:1px solid #fff;border-radius:50%;'></i>Offline</div></div></li>"
				  $('#append2'+key).append(appendStatus);
			  }
		  });
		});
	});
	
  } else {
    // No user is signed in.
	location = 'index.html'
  }
});

function sendMessage(){
	var theDiv = document.getElementById('displayBox');
	var message = document.getElementById("messageInput").value;
	var currentProperty = localStorage.getItem("prop");
	var user = firebase.auth().currentUser;
	//date
	var date = new Date;
	day = date.getDate();
	month = date.getMonth() + 1;										
	year = date.getFullYear();
	var newDate = [day, month, year].join('/');
	var db = firebase.database();
	//time
	hours = date.getHours(); // => 9
	mins = date.getMinutes(); // =>  30
	var time = [hours, mins].join(':');
	console.log(time);
	
	var messageDetails = {
		"uid": user.uid,
		"message": message,
		"date": newDate,
		"time": time
		}
		
	if(message == ''){
		document.getElementById("messageInput").style.border = '1px solid red';
	}
	else{
		db.ref('addresses/'+currentProperty+'/chat/group').push(messageDetails).then(function(){
			document.getElementById("messageInput").value = '';
			theDiv.scrollTop = '99999';
		});
	}
}

很抱歉发了这么长的帖子,但是有谁知道为什么当页面刷新时,消息会聚集在一起购买发送消息的用户?

解决该问题的任何解决方案也将非常有帮助。

提前致谢。

最佳答案

我建议更改存储消息时间戳的方式。我会像这样将它们存储为 firebase 时间戳:https://firebase.google.com/docs/reference/js/firebase.database.ServerValue

然后当您拉取它们时,您想要使用 orderByChild 然后从此处找到的检索数据信息中使用 startAt:https://firebase.google.com/docs/database/admin/retrieve-data

这将根据时间戳而不是 key 对消息进行排序。

关于javascript - 使用 Firebase 数据库 JavaScript 在 Web 应用程序上进行即时聊天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50158527/

相关文章:

jquery - 闪过 jquery 幻灯片

firebase - 如何批量删除 Firebase 匿名用户

javascript - angular1 中的范围和触发器

javascript - Codekit 忽略 .jshintrc

javascript - JQuery mousedown 与 setInterval 无限

javascript - 输入文本字段旁边的按钮

javascript - React 中的 Axios get 方法响应无法在我的博客应用程序中显示从 firebase 作为数组获取数据

python - 安装pyrebase返回错误

javascript - mootools 的负边距

php - 在java脚本中解析HTML标签的最佳方法