Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state

You could send messages via a proxy function that waits for the readyState to be 1.

this.send = function (message, callback) {
    this.waitForConnection(function () {
        ws.send(message);
        if (typeof callback !== 'undefined') {
          callback();
        }
    }, 1000);
};

this.waitForConnection = function (callback, interval) {
    if (ws.readyState === 1) {
        callback();
    } else {
        var that = this;
        // optional: implement backoff for interval here
        setTimeout(function () {
            that.waitForConnection(callback, interval);
        }, interval);
    }
};

Then use this.send in place of ws.send, and put the code that should be run afterwards in a callback:

this.ident = function () {
    var session = "Test";
    this.send(session, function () {
        window.identified = true;
        theText.value = "Hello!";
        say.click();
        theText.disabled = false;
    });
};

For something more streamlined you could look into promises.


This error raised because you are sending your message before the WebSocket connection is established.

You can solve it by doing this simply:

conn.onopen = () => conn.send("Message");

This onopen function waits for you websocket connection to establish before sending your message.


if you use one websocket client object and connect from random app places then object can be in connecting mode (concurent access).

if you want to exchange through only one websoket then create class with promise and keep it in property

class Ws {
  get newClientPromise() {
    return new Promise((resolve, reject) => {
      let wsClient = new WebSocket("ws://demos.kaazing.com/echo");
      console.log(wsClient)
      wsClient.onopen = () => {
        console.log("connected");
        resolve(wsClient);
      };
      wsClient.onerror = error => reject(error);
    })
  }
  get clientPromise() {
    if (!this.promise) {
      this.promise = this.newClientPromise
    }
    return this.promise;
  }
}

create singleton

window.wsSingleton = new Ws()

use clientPromise property in any place of app

window.wsSingleton.clientPromise
  .then( wsClient =>{wsClient.send('data'); console.log('sended')})
  .catch( error => alert(error) )

http://jsfiddle.net/adqu7q58/11/