How to point a WebSocket to the current server

ajax, javascript, websocket

Solution

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).

Problem

I have a Jetty 8 server running (hopefully soon with websockets). If I want to send some data to the server with an ajax call, I can do this: ``` $.ajax({ url: "ajax?a=getSomeData" }); ``` In this scenario, if I connect to my server at `192.168.1.100`, the real url where it will get the data from, will be `192.168.1.100/ajax?a=getSomeData`, but if I connect to another server running the same software at `192.168.1.200`, the url will be `192.168.1.200/ajax?a=getSomeData`. But if I want to accomplish the same thing using WebSockets, I cannot find how to do it: ``` var socket = new WebSocket('ws://www.example.com/'); ``` Works. But I want something like a relative url: ``` var socket = new WebSocket('ws://sockets?a=getSomeData'); ``` So that - like the ajax request - if I were connecting to my server at `192.168.1.100`, the url will be `192.168.1.100/sockets?a=getSomeData`, and if I connect to `192.168.1.200`, the url will be `192.168.1.200/sockets?a=getSomeData`. How can I accomplish this?

Original source