title: How to work around Safari 10.1 error "Failed to send WebSocket frame"?
body: <p>It seems that the WebSocket API in Safari 10.1 has a maximum amount of binary data that it can buffer and then the next message sent gets the error "WebSocket connection to ... failed: Failed to send WebSocket frame."</p>
  
  <p>Safari then closes the connection with code 1006 (CLOSE_ABNORMAL).</p>
  
  <p>WebSockets are <a href="https://html.spec.whatwg.org/multipage/comms.html#dom-websocket-bufferedamount" rel="noreferrer">supposed to report the <code>bufferedAmount</code></a> - but Safari always reports <code>0</code> until <em>after</em> the error occurs and the connection is closed.</p>
  
  <p>I tried just doing 100ms a setTimeout between each message, and that seems to work in the case of small chunks of data, but it seems brittle and large chunks still get errors when I send my closing JSON message, even with a longer delay.</p>
  
  <p>You can <a href="https://speech-to-text-demo.mybluemix.net/" rel="noreferrer">see the bug in action here</a> - the "Play Sample" buttons work in Safari 10.03 but error in 10.1. (<a href="https://github.com/watson-developer-cloud/speech-javascript-sdk/blob/v0.32.3/speech-to-text/recognize-stream.js" rel="noreferrer">Code that handles the WebSocket connection.</a>)</p>
  
  <p>Any ideas on how to work around this? Or what the limit even is? I know that Safari is Open Source, but I'm not sure where to look.</p>
  
  <p>Update: here's a simpler example:</p>
  
  <pre><code>// this fails in Safari 10.1 but works in 10.03 (and other browsers)
  var ws = new WebSocket('wss://echo.websocket.org');
  
  ws.onerror = function(evt) {
    // Not sure why, but error events seem to have no useful information
    // The console, however, will have the following error:
    // WebSocket connection to 'wss://echo.websocket.org/' failed: Failed to send WebSocket frame.
    console.log("WebSocket error - see console for message");
  }
  ws.onclose = function(evt) {
    console.log(`WebSocket closed with code: ${evt.code}, reason: ${evt.reason}`);
  }
  
  ws.onopen = function() {
    console.log('sending first binary message');
    ws.send(new Uint8Array(23085));
    console.log('bufferedAmount is ' + ws.bufferedAmount);
  
    // this gets the error
    console.log('sending second binary message');
    ws.send(new Uint8Array(23085));
    console.log('bufferedAmount is ' + ws.bufferedAmount);
  
    console.log('sending third binary message');
    ws.send(new Uint8Array(23085));
    console.log('bufferedAmount is ' + ws.bufferedAmount);
  
    ws.close();
  }
  </code></pre>
  
  <p><a href="https://jsfiddle.net/yta2mjuf/2/" rel="noreferrer">https://jsfiddle.net/yta2mjuf/2/</a></p>
  
  <p>The second message gets an error closes the connection, and after the third message, <code>bufferedAmount</code> is 23093.</p>