The WebSocket object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection.

To construct a WebSocket, use the WebSocket() constructor.


WebSocket(url[, protocols])
Returns a newly created WebSocket object.


The binary data type used by the connection.
WebSocket.bufferedAmount Read only
The number of bytes of queued data.
WebSocket.extensions Read only
The extensions selected by the server.
An event listener to be called when the connection is closed.
An event listener to be called when an error occurs.
An event listener to be called when a message is received from the server.
An event listener to be called when the connection is opened.
WebSocket.protocol Read only
The sub-protocol selected by the server.
WebSocket.readyState Read only
The current state of the connection.
WebSocket.url Read only
The absolute URL of the WebSocket.


WebSocket.close([code[, reason]])
Closes the connection.
Enqueues data to be transmitted.


// Create WebSocket connection.
const socket = new WebSocket('ws://localhost:8080');

// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ',;


Specification Status Comment
HTML Living Standard
The definition of 'WebSocket' in that specification.
Living Standard Initial definition

Browser compatibility

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) 4.0 (2.0)[1] (Yes) (Yes) (Yes)
Sub-protocol support ? ? 6.0 (6.0) ? ? ?
Feature Android Edge Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support ? (Yes) 7.0 (7.0)[1] ? ? (Yes)
Sub-protocol support ? ? 7.0 (7.0) ? ? ?

[1] Starting in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3), the constructor is prefixed; you will need to use MozWebSocket(): var mySocket = new MozWebSocket("");

The extensions attribute was not supported in Gecko until Gecko 8.0.

Prior to Gecko 11.0 (Firefox 11.0 / Thunderbird 11.0 / SeaMonkey 2.8), outbound messages sent using the send() method were limited to 16 MB. They can now be up to 2 GB in size.

See also