WebSocket: WebSocket() constructor

The WebSocket() constructor returns a new WebSocket object.

Syntax

js

new WebSocket(url)
new WebSocket(url, protocols)

Parameters

url

The URL to which to connect; this should be the URL to which the WebSocket server will respond.

protocols Optional

Either a single protocol string or an array of protocol strings. These strings are used to indicate sub-protocols, so that a single server can implement multiple WebSocket sub-protocols (for example, you might want one server to be able to handle different types of interactions depending on the specified protocol).

If it is omitted, an empty array is used by default, i.e. [].

Exceptions

SyntaxError DOMException

Thrown if:

  • parsing of url fails
  • url has a scheme other than ws or wss
  • url has a fragment
  • any of the values in protocols occur more than once, or otherwise fail to match the requirements for elements that comprise the value of Sec-WebSocket-Protocol fields as defined by the WebSocket Protocol specification

Specifications

Specification
WebSockets Standard
# ref-for-dom-websocket-websocket①

Browser compatibility

BCD tables only load in the browser

See also

  • RFC 6455 (the WebSocket Protocol specification)