To construct a WebSocket URI relative to the page URI, you need to follow these steps:
-
Get the current page's URI: You can access the current page's URI using JavaScript using the
window.location
object. Thewindow.location.href
property returns the complete URL as a string. -
Extract the protocol, hostname, and port: Parse the current page's URI to extract the protocol (e.g.,
http
orhttps
), hostname (e.g.,localhost
orexample.com
), and port if specified. -
Determine the WebSocket protocol: If the page is served over
http
, the WebSocket protocol will bews
. If the page is served overhttps
, the WebSocket protocol will bewss
. -
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.