WebSocket: WebSocket() constructor
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.
* Some parts of this feature may have varying levels of support.
Note: This feature is available inWeb Workers.
TheWebSocket() constructor returns a newWebSocket object and immediately attempts to establish a connection to the specified WebSocket URL.
In this article
Syntax
new WebSocket(url)new WebSocket(url, protocols)Parameters
urlThe URL of the target WebSocket server to connect to.The URL must use one of the following schemes:
ws,wss,http, orhttps, and cannot include aURL fragment.If a relative URL is provided, it is relative to the base URL of the calling script.protocolsOptionalA single string or an array of strings representing thesub-protocol(s) that the client would like to use, in order of preference.If it is omitted, an empty array is used by default, i.e.,
[].A single server can implement multiple WebSocket sub-protocols, and handle different types of interactions depending on the specified value.Note however that only one sub-protocol can be selected per connection.
The allowed values are those that can be specified in the
Sec-WebSocket-ProtocolHTTP header.These are values selected from theIANA WebSocket Subprotocol Name Registry, such assoap,wamp,shipand so on, or may be a custom name jointly understood by the client and the server.Note:The connection is not established until the sub-protocol is negotiated with the server.The selected protocol can then be read from
WebSocket.protocol: it will be the empty string if a connection cannot be established.
Exceptions
SyntaxErrorDOMExceptionThrown if:
Examples
The examples below show how you might connect to aWebSocket.
The code below shows how we can connect to a socket using a URL with thewss scheme:
const wssWebSocket = new WebSocket("wss://websocket.example.org");console.log(wssWebSocket.url); // 'wss://websocket.example.org'// Do something with socketwssWebSocket.close();The code for connecting to an HTTPS URL is nearly the same.Under the hood the browser resolves this to a "WSS" connection, so theWebSocket.url will have the scheme "wss:".
const httpsWebSocket = new WebSocket("https://websocket.example.org");console.log(httpsWebSocket.url); // 'wss://websocket.example.org'// Do something with sockethttpsWebSocket.close();We can also resolve relative URLs.The absolute URL will depend on the base URL of the context in which it is called.
relativeWebSocket = new WebSocket("/local/url");// Do something with socketrelativeWebSocket.close();Specifications
| Specification |
|---|
| WebSockets> # ref-for-dom-websocket-websocket①> |
Browser compatibility
See also
- RFC 6455 (the WebSocket Protocol specification)