JavaScript
Show the Message History
You want your users to see the events in the Conversation. You can filter based on the kind of event to determine how to format the event to be added to the message feed. Add a handleEvent function with this code to chat.js:
function handleEvent(event) {
let formattedMessage;
switch (event.kind) {
case "member:invited":
formattedMessage = `${event.body.user.name} was invited.<br/>`;
break;
case "member:joined":
formattedMessage = `${event.body.user.name} joined.<br/>`;
break;
case "member:left":
formattedMessage = `${event.body.user.name} left.<br/>`;
break;
case "message:text":
const sender = {
displayName: event.from.displayName,
memberId: event.from.memberId,
userName: event.from.user.name,
userId: event.from.user.id,
};
formattedMessage = formatMessage(sender, event);
break;
}
messageFeed.innerHTML = messageFeed.innerHTML + formattedMessage;
}
In this example, you will use the identity of the user to distinguish between messages sent by them and those received from other users by displaying them in a different color. Create a formatMessage function for this, by adding the following code to chat.js:
function formatMessage(sender, message) {
const rawDate = new Date(Date.parse(message.timestamp));
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
};
const formattedDate = rawDate.toLocaleDateString(undefined, options);
let text = "";
if (message.from.memberId !== myMember.id) {
text = `<span style="color:red">${sender.userName.replace(/</g,"<")} (${formattedDate}): <b>${message.body.text.replace(/</g,"<")}</b></span>`;
} else {
text = `me (${formattedDate}): <b>${message.body.text.replace(/</g,"<")}</b>`;
}
return text + "<br />";
}
Finally, you need to set up an event listener for any new incoming events. You can do this by listening for conversationEvent on the client. Add the following to the bottom of the run function:
client.on("conversationEvent", (event) => {
handleEvent(event);
});
Creating a web-based chat app
Create a web application that enables users to message each other
手順
1
Introduction to this task2
Prerequisites3
Create a Vonage Application4
Create a conversation5
Create the users6
Add users to the conversation7
Generate JWTs8
Install Client SDK9
Create the UI10
Authenticate your Users11
Instantiate VonageClient and create a Session12
Show the message history13
Send a message14
Run your application15
What's next?