files/en-us/web/api/websocket/close/index.md
{{APIRef("WebSockets API")}}{{AvailableInWorkers}}
The WebSocket.close() method closes the
{{domxref("WebSocket")}} connection or connection attempt, if any. If the connection is
already CLOSED, this method does nothing.
[!NOTE] The process of closing the connection begins with a closing handshake, and the
close()method does not discard previously-sent messages before starting that closing handshake; even if the user agent is still busy sending those messages, the handshake will only start after the messages are sent.
close()
close(code)
close(code, reason)
code {{optional_inline}}
1000 for a normal closure, or otherwise to another standard value in the range 1001-1015 that indicates the actual reason the connection was closed.code parameter overrides the automatic setting of the close code for the connection, and instead sets a custom code.
The value must be an integer: either 1000, or else a custom code of your choosing in the range 3000-4999. If you specify a code value, you should also specify a reason value.reason {{optional_inline}}
: A string providing a custom WebSocket connection close reason (a concise human-readable prose explanation for the closure). The value must be no longer than 123 bytes (encoded in UTF-8).
[!NOTE] Because UTF-8 uses two to four bytes to encode any non-ASCII characters, a 123-character
reasonvalue containing non-ASCII characters would exceed the 123-byte limit.
If you specify a reason value, you should also specify a code value.
None ({{jsxref("undefined")}}).
InvalidAccessError {{domxref("DOMException")}}
code is neither an integer equal to 1000 nor an integer in the range 3000 – 4999.SyntaxError {{domxref("DOMException")}}
reason value is longer than 123 bytes.{{Specifications}}
{{Compat}}