Web APIs
WebSocket()
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
| Name | Type | Description |
|---|---|---|
| url | string | URL | WebSocket endpoint. |
| protocols | string | 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();}})()