WebSocket: close() method
Baseline
Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Note: This feature is available in Web Workers.
The WebSocket.close() method closes the
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.
Syntax
close()
close(code)
close(code, reason)
Parameters
codeOptional-
An integer WebSocket connection close code value indicating a reason for closure:
- If unspecified, the close frame sent to the server contains no status code, and the server treats the close code as
1005("No Status Received"). Thecodeof the resultingcloseevent is taken from the server's reply: it is usually also1005, because servers typically echo the status code they received, but the server may send a different code. If the connection is not closed cleanly, the code is set to another standard value, such as1006. - If specified, the value of this
codeparameter overrides the automatic setting of the close code for the connection, and instead sets a custom code. The value must be an integer: either1000, or else a custom code of your choosing in the range3000-4999. If you specify acodevalue, you should also specify areasonvalue.
- If unspecified, the close frame sent to the server contains no status code, and the server treats the close code as
reasonOptional-
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
reasonvalue, you should also specify acodevalue.
Return value
None (undefined).
Exceptions
InvalidAccessErrorDOMException-
Thrown if
codeis neither an integer equal to1000nor an integer in the range3000–4999. SyntaxErrorDOMException-
Thrown if the UTF-8-encoded
reasonvalue is longer than 123 bytes.
Specifications
| Specification |
|---|
| WebSockets> # dom-websocket-close> |
Browser compatibility
See also
- RFC 6455 (the WebSocket Protocol specification)