Sometimes, we want to close WebSocket connection with JavaScript.
In this article, we’ll look at how to close WebSocket connection with JavaScript.
How to close WebSocket connection with JavaScript?
To close WebSocket connection with JavaScript, we remove the onclose
handler and then we call close
.
For instance, we write
window.onbeforeunload = () => {
websocket.onclose = () => {};
websocket.close();
};
to set the onclose
property to an empty function to remove the close event handler.
Then we call close
to close the connection.
Conclusion
To close WebSocket connection with JavaScript, we remove the onclose
handler and then we call close
.