title: Closing HTML5 Web Sockets
body: <p><a href="https://stackoverflow.com/questions/4812686/closing-websocket-correctly-html5-javascript">HTML5 Web Sockets behave strangely</a> if users are refreshing the page, or navigating
  away from it. During reloading of the page, the socket connections between webserver and browser seem to stay open, and are closed if the page reloads in the browser, in both Firefox and Chrome. This means it works only every second time to establish a connection between browser and server, because <strong>the socket is closed by the browser on reload</strong>. The error message in the Firebug console from Firefox is "The connection to ws://.../websocket" was interrupted while the page was loading". So apparently the websocket connection is still open when the page is reloaded, which means the connection is closed during page load instead of opened every second page load. Log files read for instance like this (created with the <a href="https://github.com/websocket-rails/websocket-rails" rel="nofollow noreferrer">Websocket-Rails</a> gem)</p>
  
  <pre><code>==&gt; first page load
  [ConnectionManager] Connection opened: #&lt;Connection::fef69428febee72f4830&gt;
  [Channel] #&lt;Connection::fef69428febee72f4830&gt; subscribed to channel xyz
  
  ==&gt; second page load
  [Channel] #&lt;Connection::dfc4b33090b95826e08e&gt; unsubscribed from channel xyz
  [ConnectionManager] Connection closed: #&lt;Connection::dfc4b33090b95826e08e&gt;
  </code></pre>
  
  <p>Is there are way to close all open sockets and connections in the <code>onbeforeunload</code> Javascript event, something
  like (in Coffeescript)..</p>
  
  <pre><code>  window.onbeforeunload = () -&gt;
      close_all_sockets()
  </code></pre>