Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. WebSocket
  4. close()

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 inWeb Workers.

TheWebSocket.close() method closes theWebSocket connection or connection attempt, if any. If the connection isalreadyCLOSED, this method does nothing.

Note:The process of closing the connection begins with aclosing handshake, and theclose() 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

js
close()close(code)close(code, reason)

Parameters

codeOptional

An integerWebSocket connection close code value indicating a reason for closure:

  • If unspecified, a close code for the connection is automatically set: to1000 for a normal closure, or otherwise toanother standard value in the range1001-1015 that indicates the actual reason the connection was closed.
  • If specified, the value of thiscode parameter 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 acode value, you should also specify areason value.
reasonOptional

A string providing a customWebSocket 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:BecauseUTF-8 uses two to four bytes to encode any non-ASCII characters, a 123-characterreason value containing non-ASCII characters would exceed the 123-byte limit.

If you specify areason value, you should also specify acode value.

Return value

None (undefined).

Exceptions

InvalidAccessErrorDOMException

Thrown ifcode is neither an integer equal to1000 nor an integer in the range30004999.

SyntaxErrorDOMException

Thrown if the UTF-8-encodedreason value is longer than 123 bytes.

Specifications

Specification
WebSockets
# dom-websocket-close

Browser compatibility

See also

  • RFC 6455 (the WebSocket Protocol specification)

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp