How to get the current status of a javascript websocket connection

JavascriptWebsocketClient

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohnrideView Question on Stackoverflow
Solution 1 - JavascriptJohnrideView Answer on Stackoverflow