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

前端 未结 8 1499
轻奢々
轻奢々 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:02

    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
    

提交回复
热议问题