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:/
Using the Window.URL API - https://developer.mozilla.org/en-US/docs/Web/API/Window/URL
Works with http(s), ports etc.
var url = new URL('/path/to/websocket', window.location.href);
url.protocol = url.protocol.replace('http', 'ws');
url.href // => ws://www.example.com:9999/path/to/websocket
In typescript:
export class WebsocketUtils {
public static websocketUrlByPath(path) {
return this.websocketProtocolByLocation() +
window.location.hostname +
this.websocketPortWithColonByLocation() +
window.location.pathname +
path;
}
private static websocketProtocolByLocation() {
return window.location.protocol === "https:" ? "wss://" : "ws://";
}
private static websocketPortWithColonByLocation() {
const defaultPort = window.location.protocol === "https:" ? "443" : "80";
if (window.location.port !== defaultPort) {
return ":" + window.location.port;
} else {
return "";
}
}
}
Usage:
alert(WebsocketUtils.websocketUrlByPath("/websocket"));