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])
WebSocket
object.WebSocket.binaryType
WebSocket.bufferedAmount
Read only
WebSocket.extensions
Read only
WebSocket.onclose
WebSocket.onerror
WebSocket.onmessage
WebSocket.onopen
WebSocket.protocol
Read only
WebSocket.readyState
Read only
WebSocket.url
Read only
WebSocket.close([code[, reason]])
WebSocket.send(data)
// 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 ', event.data); });
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'WebSocket' in that specification. | Living Standard | Initial definition |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | Yes | Yes | 11
|
? | Yes | Yes |
WebSocket() constructor |
Yes | ? | 7
|
? | Yes | ? |
binaryType |
Yes | ? | Yes | ? | Yes | ? |
bufferedAmount |
Yes | ? | Yes | ? | Yes | ? |
close |
Yes | ? | 8
|
? | Yes | ? |
extensions |
Yes | ? | 8 | ? | Yes | ? |
onclose |
Yes | ? | Yes | ? | Yes | ? |
onerror |
Yes | ? | Yes | ? | Yes | ? |
onmessage |
Yes | ? | Yes | ? | Yes | ? |
onopen |
Yes | ? | Yes | ? | Yes | ? |
protocol |
Yes | ? | Yes | ? | Yes | ? |
readyState |
Yes | ? | Yes | ? | Yes | ? |
send |
Yes | ? | 18
|
? | Yes | ? |
url |
Yes | ? | Yes | ? | Yes | ? |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | ? | ? | Yes | 14
|
? | Yes | ? |
WebSocket() constructor |
? | Yes | ? | 7 | ? | ? | ? |
binaryType |
? | Yes | ? | Yes | ? | ? | ? |
bufferedAmount |
? | Yes | ? | Yes | ? | ? | ? |
close |
? | Yes | ? | Yes | ? | ? | ? |
extensions |
? | Yes | ? | 8 | ? | ? | ? |
onclose |
? | Yes | ? | Yes | ? | ? | ? |
onerror |
? | Yes | ? | Yes | ? | ? | ? |
onmessage |
? | Yes | ? | Yes | ? | ? | ? |
onopen |
? | Yes | ? | Yes | ? | ? | ? |
protocol |
? | Yes | ? | Yes | ? | ? | ? |
readyState |
? | Yes | ? | Yes | ? | ? | ? |
send |
? | Yes | ? | Yes | ? | ? | ? |
url |
? | Yes | ? | Yes | ? | ? | ? |
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/WebSocket