Web APIs

WebSocket()

Try the free JavaScript compiler

Starts opening a WebSocket connection to a server; returns before the connection is open.

Formal Syntax & Structure

javascript syntaxjavascript
new WebSocket(url, [protocols])

Parameters & Attributes

NameTypeDescription
urlstring | URLWebSocket endpoint.
protocolsstring | string[]Requested subprotocols.

Return Value

WebSocket

Starts opening a WebSocket connection to a server; returns before the connection is open.

Working Example

Example Snippetjavascript
(async () => {const url=new URL("/ws",location.href);url.protocol=location.protocol==="https:"?"wss:":"ws:";const ws=new WebSocket(url);try{await new Promise((ok,no)=>{ws.onopen=ok;ws.onerror=()=>no(new Error("connection failed"));});console.log(ws.readyState===WebSocket.OPEN);}finally{ws.close();}})()
JavaScript Reference