WebSocketStream: close() method

Experimental: This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

Note: This feature is available in Web Workers.

The close() method of the WebSocketStream interface closes the WebSocket connection. The method optionally accepts an object containing a custom code and/or reason indicating why the connection was closed.

Syntax

js
close()
close(options)

Parameters

options Optional

An options object containing the following properties:

closeCode Optional

A number representing the closing code (see the full list of CloseEvent status codes).

reason Optional

A string representing a human-readable description of the reason why the socket connection is closed. The maximum allowed length for a reason string is 123 bytes. The string is automatically encoded as UTF-8 when the function is invoked.

Note: Depending on the server setup and status code you use, the server may choose to ignore a custom code in favor of a valid code that is correct for the closing reason. Valid codes are 1000, and any code within the range 3000 to 4999, inclusive.

Return value

None (undefined).

Exceptions

SyntaxError DOMException

Thrown if the provided reason is longer than the maximum allowed length of 123 bytes.

Examples

js
const wsURL = "wss://127.0.0.1/";
const wss = new WebSocketStream(wsURL);

setTimeout(() => {
  wss.close({
    closeCode: 1000,
    reason: "That's all folks",
  });
}, 10000);

Specifications

Not currently a part of any specification. See https://github.com/whatwg/websockets/pull/48 for standardization progress.

Browser compatibility

desktop mobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
close
Experimental
Chrome – Full support
Chrome 124 (Release date: 2024-04-16)
footnote Full support
Edge – Full support
Edge 124 (Release date: 2024-04-18)
footnote Full support
Firefox – No support
Firefox
footnote No support
Opera – Full support
Opera 110 (Release date: 2024-05-14)
footnote Full support
Safari – No support
Safari
footnote No support
Chrome Android – Full support
Chrome Android 124 (Release date: 2024-04-16)
footnote Full support
Firefox for Android – No support
Firefox for Android
footnote No support
Opera Android – Full support
Opera Android 82 (Release date: 2024-05-02)
footnote Full support
Safari on iOS – No support
Safari on iOS
footnote No support
Samsung Internet – Full support
Samsung Internet 27 (Release date: 2024-11-06)
footnote Full support
WebView Android – Full support
WebView Android 124 (Release date: 2024-04-16)
footnote Full support
WebView on iOS – No support
WebView on iOS
footnote No support

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support
Experimental. Expect behavior to change in the future.

See also