How to construct a WebSocket URI relative to the page URI?

23 min read

To construct a WebSocket URI relative to the page URI, you need to follow these steps:

  1. Get the current page's URI: You can access the current page's URI using JavaScript using the window.location object. The window.location.href property returns the complete URL as a string.

  2. Extract the protocol, hostname, and port: Parse the current page's URI to extract the protocol (e.g., http or https), hostname (e.g., localhost or example.com), and port if specified.

  3. Determine the WebSocket protocol: If the page is served over http, the WebSocket protocol will be ws. If the page is served over https, the WebSocket protocol will be wss.

  4. Create the WebSocket URI: Combine the WebSocket protocol, hostname, and port (if needed) into a single string to form the WebSocket URI.

Here's an example of how this can be done in JavaScript:

// Get current page URI
var pageURI = window.location.href;

// Parse the current page URI to extract protocol, hostname, and port
var parser = document.createElement('a');
parser.href = pageURI;
var protocol = parser.protocol.replace(/^http/, 'ws');
var hostname = parser.hostname;
var port = parser.port;

// Construct the WebSocket URI
var websocketURI = protocol + '://' + hostname;
if (port) {
  websocketURI += ':' + port;
}

console.log(websocketURI);

By following these steps, you can construct a WebSocket URI relative to the current page's URI.