title: Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state
body: <p>When my page loads, I try to <code>send</code> a message to the server to initiate a connection, but it's not working. This script block is near the top of my file:</p>
  
  <pre><code>var connection = new WrapperWS();
  connection.ident();
  // var autoIdent = window.addEventListener('load', connection.ident(), false);
  </code></pre>
  
  <p>Most of the time, I see the error in the title:</p>
  
  <blockquote>
    <p>Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state</p>
  </blockquote>
  
  <p>So I tried to <code>catch</code> the exception, as you can see below, but now it seems <code>InvalidStateError</code> is not defined and that produces a <code>ReferenceError</code>.</p>
  
  <p>Here's the wrapper object for my websocket connection:</p>
  
  <pre><code>// Define WrapperWS
  
  function WrapperWS() {
      if ("WebSocket" in window) {
          var ws = new WebSocket("ws://server:8000/");
          var self = this;
  
          ws.onopen = function () {
              console.log("Opening a connection...");
              window.identified = false;
          };
          ws.onclose = function (evt) {
              console.log("I'm sorry. Bye!");
          };
          ws.onmessage = function (evt) {
              // handle messages here
          };
          ws.onerror = function (evt) {
              console.log("ERR: " + evt.data);
          };
  
          this.write = function () {
              if (!window.identified) {
                  connection.ident();
                  console.debug("Wasn't identified earlier. It is now.");
              }
              ws.send(theText.value);
          };
  
          this.ident = function () {
              var session = "Test";
              try {
                  ws.send(session);
              } catch (error) {
                  if (error instanceof InvalidStateError) {
                      // possibly still 'CONNECTING'
                      if (ws.readyState !== 1) {
                          var waitSend = setInterval(ws.send(session), 1000);
                      }
                  }
              }
          window.identified = true;
              theText.value = "Hello!";
              say.click();
              theText.disabled = false;
          };
  
      };
  
  }
  </code></pre>
  
  <p>I am testing using Chromium on Ubuntu.</p>