How to Check if a WebSocket Is Connected in JavaScript?

Checking websocket for successful connection in JavaScript

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

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

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

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

ws.onopen = function (event) {
    console.log('connected');
};

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

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

ws.addEventListener('open', function (event) {
    console.log('connected');
});

The open event is fired when the connection with a WebSocket is opened. When this happens, the readyState of the WebSocket connection changes to OPEN.


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