How to Disconnect a WebSocket Connection in JavaScript?

Find out how to close a websocket connection in JavaScript

To close a WebSocket connection, you can simply use the WebSocket.close() method, for example, like so:

const ws = new WebSocket('ws://localhost:8080');

// ...

ws.close();

If the readyState of the WebSocket connection is already in the CLOSE state, then the method does nothing. However, in all other cases, it closes the WebSocket connection.

If you wish to state the status code or the reason for closing the socket connection, then you may provide the following, optional, parameters to the WebSocket.close() method:

  • A closing status code as the only argument, or;
  • A reason text (that's max 123 bytes of UTF-8 text) as the only argument, or;
  • A combination of both; the closing status code and the reason (as first and second arguments respectively).

This means that the WebSocket.close() method has the following method signatures:

WebSocket.close(code);
WebSocket.close(reason);
WebSocket.close(code, reason);

The closing status code and the reason are accessible via the CloseEvent.code and CloseEvent.reason read-only properties, which are passed to the event handler of the close event.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.