Writing the chat frontend
We have one tiny server-side piece to do before we write our chat client, and that is to write the static file-serving chat handler. It looks almost exactly like our index handler:
Writing the HTML#
With that done, let's talk about writing
chat.html. We are going to keep the HTML and CSS fairly minimal. It will be a list of messages, stored in a div, with a separate div and button for the chat box and send message button.
The base of it will look like this, and we will be filling in the
<script> tag with all of the parts necessary to interact with our server.
Beyond thanking frontend specialists, there are a few key things to note with the above. We have two important HTML elements with
messages div, which will contain all of our chat messages, and the
message-text input which will hold the value for whatever message our user is sending. The
messages div also has the
aria-live="polite" attribute, which is important for the accessibility of screen readers. ARIA live regions are essential for any part of a page that will change dynamically. We are setting this one to
"polite" to indicate that it should be shared with the reader so long as they are idle.
We have two onclick handlers,
On that note, we should talk about our requirements and then write our code.
Our frontend will need to send and retrieve messages. Retrieving messages has a few cases to handle:
There's the initial page load, where we fetch the ten most recent messages.
We also want to fetch messages older or newer than a given time.
Retrieved messages need to be either appended to our
messagesdiv if they are newer, or prepended if they are older.
Finally, because we are using polling, we want to continually check to see if there are new messages.
Let's start with sending messages.