I am trying to make a basic chat application with rooms using flask-socketio, but whenever I run the code on my browser, a weird error comes on the console and I am not able to send any messages through the web socket. The error that comes is:

channel.js:56 Uncaught TypeError: Cannot read property 'addEventListener' of null
    at r.<anonymous> (channel.js:56)
    at r.emit (socket.io.js:1647)
    at r.emit (socket.io.js:813)
    at r.onconnect (socket.io.js:1001)
    at r.onpacket (socket.io.js:897)
    at r.<anonymous> (socket.io.js:1512)
    at r.emit (socket.io.js:1647)
    at r.ondecoded (socket.io.js:428)
    at s.<anonymous> (socket.io.js:1512)
    at s.r.emit (socket.io.js:4389)

My main code is like: whenever the user types in a message and presses the 'send' button, I am sending the message to the server, which is broadcasting it to all the other users in that particular room. But the problem is that whenever I press the 'send' button, above error comes in the console, with no message being sent.

Relevant code:


<div id="chat-box" class="list-group">
    <ul id="chat">
        {%- if messages -%} 
            {%- for message in messages -%}
                {{ message[0] }} sent on {{ message[1] }} : {{ message [2] }} {{'\n'}}
            {%- endfor -%}
            {{ '----- These are old messages -----' }}{{- '\n' -}}
        {%- endif -%}

<div id="message-box">                
    <input id="comment" size="50" autocomplete="off" autofocus>       
    <button id="send-button" type="reset">Send</button>
<script type="text/javascript" src="../static/channel.js"></script>


document.getElementById("send-button").addEventListener('click', {
    let timestamp = new Date;
    timestamp = timestamp.toLocaleTimeString();
    let msg = document.getElementById("comment").value;
    socket.emit('send message', msg, timestamp);
    document.getElementById("comment").value = '';

socket.on('announce message', data => {
    const li = document.createElement('li');
    li.innerHTML = `${data.user}`  ' sent on  ' + `${data.timestamp}` + `${data.msg}`

And the application.py file:

@socketio.on('send message')
def send_msg(msg, timestamp):
    room = session.get('current_channel')
    channelsMessages[room].append([timestamp, session.get('username'), msg])
    emit('announce message', {'user': session.get('username'), 'timestamp': timestamp, 'msg': msg}, room=room)

But still, the ul remains empty, and I am not able to understand how, even though the previous messages show up perfectly. Also, I am storing the messages, channels and the users in the server side in dictionary and lists, respectively.

Any help would be kindly appreciated.

You must log in to answer this question.

Browse other questions tagged .