Javascript

  • Fetch live chat messages from API every 5 seconds
  • Only new messages would be added to the screen display
  • New messages would be added to the bottom, while old messages would move up
  • Optional: Messages would be removed from screen display if it exceeds the 「display_item」 variable
<script>

imnobby_fetchLiveChat();

var t = setInterval(imnobby_fetchLiveChat, 5000);

async function imnobby_fetchLiveChat() {

 let chat_api_url = "https://www.your-domain.com/your-api-endpoint/"; // YouTube API format used in example
 let response = await fetch(chat_api_url);

 if (response.status === 200) {

 let data = await response.text();
 let data_obj = JSON.parse(data);

 let chat_array = [];

 for (var i = 0; i < data_obj.length; i++) {

 // this_id = data_obj[i].id.slice(-64);
 // this_name = data_obj[i].name;
 // this_msg = data_obj[i].msg;
 // this_ts = data_obj[i].ts;

 var this_array = new Array();
 this_array["id"] = data_obj[i].id.slice(-64); // data_obj[i].id; // this_id
 this_array["name"] = data_obj[i].name; // this_name
 this_array["msg"] = data_obj[i].msg; // this_msg
 this_array["ts"] = data_obj[i].ts; // this_ts

 chat_array.push(this_array);

 }

 // let display_items = 65;
 // let remove_items = data_obj.length - display_items;
 // chat_array.splice(0, remove_items);

 imnobby_displayChatItems(chat_array);

 }
}

function imnobby_displayChatItems(chat_array) {

 console.log("imnobby_displayChatItems");

 let chatbox = document.getElementById('chatbox');
 let len = chat_array.length;

 let current_li = [];
 let remove_count = 0;

 document.querySelectorAll(".chat-item").forEach(
 function(item) {
 current_li.push(item.getAttribute('data-attr'));
 }
 );

 for (var i = 0; i < chat_array.length; i++) {

 this_id = chat_array[i]["id"];
 this_name = chat_array[i]["name"];
 this_msg = chat_array[i]["msg"];
 this_ts = chat_array[i]["ts"];

 if (!current_li.includes(this_id)) {
 remove_count++;
 }

 if (!current_li.includes(this_id)) {

 chatbox.innerHTML += '<div data-attr="' + this_id + '" class="d-flex chat-item"><p><span class="user-name">' + this_name + ' : </span><span class="user-message">' + this_msg + '</span><br><i>' + this_ts + '</i></p></div>';

 }
 }

 if (remove_count != len) {
 for (var i = 0; i < remove_count; i++) {
 console.log("remove item");
 document.querySelector(".chat-item").remove();
 }
 }

}
</script>

HTML

<div class="chatbox-warpper">
 <div id="chatbox"></div>
</div>
Related Keywords: Developer, How-to, Solved, HTML, JS, YouTube Live Streaming Chat Display, Chatroom Display Javascript, With No Web Push, Sample Code