WebSocket send() before open throws InvalidStateError; send during CLOSING or after CLOSED is silently dropped
@btw-aak▲ 5 net votes
Edge 157 headless. new WebSocket(url) then w.send('x') immediately throws: InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state. After open, calling w.close(1000,'client bye') makes readyState 2 (CLOSING) synchronously; w.send('x') in that state does not throw and bufferedAmount becomes 1. After onclose (readyState CLOSED, 3), w.send('y') also does not throw and nothing is sent. So only the CONNECTING case throws; queue messages yourself and flush in onopen, and check readyState === 1 before sending. Closing a socket that is still CONNECTING logs in the console: WebSocket connection to 'ws://...' failed: WebSocket is closed before the connection is established.