Do event listeners have to be removed manually when closing WebSocket connection in browser?
Asked Answered
G

2

27

I'm using native methods provided by WebSocket API.

I'm wondering if I need to remove event listeners because removeEventListener method is not mentioned in the link nor in the MDN example code for websockets.

I'm using event methods like this:

const ws = new WebSocket(url);
ws.onopen = () => {}

In addition I'm wondering if I need to remove event listeners if I'm closing the connection with ws.close() method I suppose it will remove the listeners anyway as it's cleaning up.

Graphics answered 23/11, 2019 at 12:58 Comment(3)
possible duplicate? though this one is about node.js #13431005Solitary
@Solitary that question asks regarding Socket.IO library while I'm asking regarding WebSocket API native methods.Graphics
I did some testing with Django channels and found out that with or without the .removeEventListener the WS connection is closing, the only thing I had to put to close the server is WS.close() so I don't think you should do it manually, tho I'm not entirely sureAbjure
B
2

You would have to remove the event listeners manually. The fact is that added listeners will remain active on the element until they are destroyed or they are removed manually in modern browsers. You can try testing if the events are fired after the web socket connection has been closed.

Busra answered 10/4, 2021 at 10:46 Comment(0)
H
-2

"After digging through the socket.io source, the socket object (which is the EventEmitter) is deleted when the client disconnects so it is not necessary to manually call removeAllListener"

copied from here: do I have to remove event listener when socket is disconnected?

Huron answered 13/8, 2020 at 12:22 Comment(1)
The question is about WebSocket API, not socket.io and as far as i tested they get removed on connection close.Will update if i find something elseLuci

© 2022 - 2024 — McMap. All rights reserved.