How to construct a WebSocket URI relative to the page URI?
Asked 07 September, 2021
Viewed 2.8K times
  • 65
Votes

I want to construct a WebSocket URI relative to the page URI at the browser side. Say, in my case convert HTTP URIs like

http://example.com:8000/path
https://example.com:8000/path

to

ws://example.com:8000/path/to/ws
wss://example.com:8000/path/to/ws

What I'm doing currently is replace the first 4 letters "http" by "ws", and append "/to/ws" to it. Is there any better way for that?

8 Answer