Skip to content

WebSocket: readyState property ​

The readyState property indicates the stage the connection is in right now.

Value ​

A number, one of the following four:

ValueConstantMeaning
0WebSocket.CONNECTINGConnecting; messages cannot be sent yet
1WebSocket.OPENConnected; messages can be sent and received
2WebSocket.CLOSINGClosing
3WebSocket.CLOSEDEnded
  • Read-only. Assigning to it throws TypeError.
  • A new connection is 0.
  • It only moves in the direction 0 → 1 → 2 → 3 and never goes back. When the connection fails or drops partway through, it goes straight from 0 or 1 to 3.

Observing changes ​

  • When it becomes 1, open fires.
  • When it becomes 3, close fires.
  • It becomes 2 immediately after close() is called; this change has no event, because it is caused by the app's own call.

Examples ​

js
const ws = new WebSocket('wss://echo.websocket.org');
ws.addEventListener('open', () => {
  console.log(ws.readyState === WebSocket.OPEN);
  ws.close();
  console.log(ws.readyState === WebSocket.CLOSING);
});

Result: once connected, logs true, then true.

Differences from the web ​

The same as on the web.

See also ​