83

Sometimes when I restart the server or there is a network failure the websocket gets closed and I would like to be able to get the current connection status at all time.

I am basically getting the following error and I want to be able to predict it :

WebSocket is already in CLOSING or CLOSED state. 
    (anonymous function) 
    InjectedScript._evaluateOn 
    InjectedScript._evaluateAndWrap 
    InjectedScript.evaluate
Johnride
  • 8,476
  • 5
  • 29
  • 39

1 Answers1

150

This is very straightforward : thereadyState property of the websocket contains the connection of the websocket at all times as specified in the WebSocket API

It will be one of the following values : CONNECTING OPEN CLOSING or CLOSED

A way to work around the error would be something like this :

if (yourWsObject.readyState !== WebSocket.CLOSED) {
   // Do your stuff...
}
Imnotapotato
  • 5,308
  • 13
  • 80
  • 147
Johnride
  • 8,476
  • 5
  • 29
  • 39
  • 9
    the correct answer for the api. A small note, `yourWsObject.readyState` will be `1` (OPEN) even if you try to connect without connection. Ive tested it with a remote backend, trying to connect from an Android emulator. after closing Wifi on my laptop and trying to connect from the emulator to the remove socket server I still got OPEN on `readyState` – Blue Bot Nov 04 '19 at 13:35
  • 2
    socket.readyState !== WebSocket.CLOSED && socket.readyState !== WebSocket.CLOSING ? true : false; – Alex Dec 09 '20 at 16:02
  • @BlueBot - Correct – kta May 15 '22 at 02:01
  • 2
    Another option might be maintain a boolean by yourself, `onopen` -> `true`, `onclose` -> `false`. – Eric Jun 16 '22 at 08:45
  • @BlueBot correct it will say OPEN in any circumstances if error or closed is not met. So i made 10 second interval to check if OPEN state is changed AND AppState.addEventListener('change'); if previous state not active and new state active then force to reconnect. – user2573099 Aug 16 '23 at 04:17