Implementing the WebSocket client
So far, you have created the course_chat_room
view and its corresponding template for students to access the course chat room. You have implemented a WebSocket consumer for the chat server and tied it with URL routing. Now, you need to build a WebSocket client to establish a connection with the WebSocket in the course chat room template and be able to send/receive messages.
You are going to implement the WebSocket client with JavaScript to open and maintain a connection in the browser. You will interact with the Document Object Model (DOM) using JavaScript.
Edit the chat/room.html
template of the chat
application and modify the include_js
and domready
blocks, as follows:
{% block include_js %}
{{ course.id|json_script:"course-id" }}
{% endblock %}
{% block domready %}
const courseId = JSON.parse(
document.getElementById('course-id').textContent
);
const url = 'ws://' + window.location.host +
...