How to Check if a WebSocket Is Disconnected in JavaScript?

Checking websocket for disconnection in JavaScript

You can check if a WebSocket is disconnected by doing either of the following:

  • Specifying a function to the WebSocket.onclose event handler property, or;
  • Using addEventListener to listen to the close event.

In either case, CloseEvent is passed to the event handler.

For example, you would use the event handler property like so:

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

ws.onclose = function (event) {
    console.log('disconnected');
};

Or, as an alternative, you could use addEventListener (to listen to the close event) like so:

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

ws.addEventListener('close', function (event) {
    console.log('disconnected');
});

The close event is fired when the connection with a WebSocket is closed. When this happens, the readyState of the WebSocket connection changes to CLOSED.


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