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

前端 未结 8 1497
轻奢々
轻奢々 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-12 23:43

    Assuming your WebSocket server is listening on the same port as from which the page is being requested, I would suggest:

    function createWebSocket(path) {
        var protocolPrefix = (window.location.protocol === 'https:') ? 'wss:' : 'ws:';
        return new WebSocket(protocolPrefix + '//' + location.host + path);
    }
    

    Then, for your case, call it as follows:

    var socket = createWebSocket(location.pathname + '/to/ws');
    

提交回复
热议问题