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

前端 未结 8 1494
轻奢々
轻奢々 2020-12-12 23:25

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:/         


        
8条回答
  •  借酒劲吻你
    2020-12-13 00:06

    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"));
    

提交回复
热议问题