How to point a WebSocket to the current server How to point a WebSocket to the current server ajax ajax

How to point a WebSocket to the current server


Just build the URL yourself:

var socket = new WebSocket("ws://" + location.host + "/whatever");

The location object is a property of the window object, and is therefore globally available.

To get only the host without the port, use location.hostname instead. If the websocket server listens on another port for example.

You can also inspect location.protocol to know if you should connect to wss (when https is used) or ws (when http is used).