In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "Building an instant messaging application implementation Home page". In daily operation, I believe that many people have doubts about building an instant messaging application implementation Home page. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "building an instant messaging application to achieve Home page". Next, please follow the editor to study!
Conversation form
Go to the static/ages/home-page.js file and add some tags in the HTML view.
Add this form to the bottom of the section where we display the "auth user" and "logout" buttons.
Page.getElementById ('conversation-form'). Onsubmit = onConversationSubmit
Now we can listen to the "submit" event to create a conversation.
Import http from'.. / http.js' import {navigate} from'.. / router.js' async function onConversationSubmit (ev) {ev.preventDefault () const form = ev.currentTarget const input = form.querySelector ('input') input.disabled = true try {const conversation = await createConversation (input.value) input.value =' 'navigate (' / conversations/' + conversation.id)} catch ( Err) {if (err.statusCode = 422) {input.setCustomValidity (err.body.errors.username)} else {alert (err.message)} setTimeout (() = > {input.focus ()} 0)} finally {input.disabled = false}} function createConversation (username) {return http.post ('/ api/conversations', {username})}
When submitting, we use the user name to make an POST request to / api/conversations and redirect to the conversation page (for the next article).
Conversation list
Again in this file, we will create the homePage () function to load the conversation asynchronously first.
Export default async function homePage () {const conversations = await getConversations (). Catch (err = > {console.error (err) return []}) / *. * /} function getConversations () {return http.get ('/ api/conversations')}
Then, add a list to the tag to render the conversation.
Add it directly below the current tag.
Const conversationsOList = page.getElementById ('conversations') for (const conversation of conversations) {conversationsOList.appendChild (renderConversation (conversation))}
Therefore, we can add each conversation to this list.
Import {avatar EscapeHTML} from'. / shared.js' function renderConversation (conversation) {const messageContent = escapeHTML (conversation.lastMessage.content) const messageDate = new Date (conversation.lastMessage.createdAt). ToLocaleString () const li = document.createElement ('li') li.dataset [' id'] = conversation.id if (conversation.hasUnreadMessages) {li.classList.add ('has-unread-messages')} Li [XSS _ clean] = ` ${avatar (conversation.otherParticipant)} ${conversation.otherParticipant.username}
${messageContent}
${messageDate} `return li}
Each conversation entry contains a link to the conversation page and displays other participant information and a preview of the last message. In addition, you can add a class to the entry using .hasUnreadMessages and use CSS to make some styling. Maybe it's bold or accentuated color.
Please note that we need to escape the content of the message. This function comes from the static/shared.js file:
Export function escapeHTML (str) {return str. Replace (/ & / g,'&'). Replace (/ / g,'>'). Replace (/'/ g,'). Replace (/'/ g,'& # 039')}
This prevents user-written messages from being displayed as HTML. If the user happens to write code similar to the following:
Alert ('lololo')
This will be very annoying because the script will be executed. So always remember to escape content from untrusted sources.
Message subscription
Last but not least, I want to subscribe to the message stream here.
Const unsubscribe = subscribeToMessages (onMessageArrive) page.addEventListener ('disconnect', unsubscribe)
Add this line to the homePage () function.
Function subscribeToMessages (cb) {return http.subscribe ('/ api/messages', cb)}
The function subscribe () returns a function that closes the underlying connection once called. That's why I passed it to the "disconnect" disconnect event; therefore, when the user leaves the page, the event stream is closed.
Async function onMessageArrive (message) {const conversationLI = document.querySelector (`li [data-id= "${message.conversationID}"] `) if (conversationLI! = = null) {conversationLI.classList.add ('has-unread-messages') conversationLI.querySelector (' a > div > p'). TextContent = message.content conversationLI.querySelector ('a > div > time'). TextContent = new Date (message.createdAt). ToLocaleString () return } let conversation try {conversation = await getConversation (message.conversationID) conversation.lastMessage = message} catch (err) {console.error (err) return} const conversationsOList = document.getElementById ('conversations') if (conversationsOList = null) {return} conversationsOList.insertAdjacentElement (' afterbegin') RenderConversation (conversation))} function getConversation (id) {return http.get ('/ api/conversations/' + id)}
Each time a new message arrives, we query the session entry in DOM. If found, we will add the has-unread-messages class to the entry and update the view. If it is not found, the message is from the new conversation you just created. Let's make a GET request to / api/conversations/ {conversationID} to get the conversation in which the message was created and put it in front of the conversation list.
At this point, the study on "Building an instant messaging application to implement the Home page" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.