websocketpurescripthalogen

Get current base URL for web page


I am running a PureScript app that is being served up by a backend Suave application in F#. In the front end, I need to open a WebSocket connection in PureScript to the backend, but part of the path needs to be dynamic based on how the backend app is running (for example on some boxes it is: ws://host1:9999/ws/blah, on others it might be ws://host2:7777/ws/blah).

So I need to get the current URL that my app is being served up on so that I can just put a ws:// on the front, and a ws/blah on the end (or somehow do a relative WebSocket path?).

I've tried doing something like:

wdw <- window
htmldoc <- document wdw
let doc = htmlDocumentToDocument htmldoc
docUrl <- url doc
connection <- WS.create (WS.URL $ "ws://" <> docUrl <> "ws/blah") []

But the document URL given has http:// on the front of it. I could hack up the string and rip that part out, but I'm hoping to find a more elegant way.

If it matters, I'm also using Halogen here so I have access to their API if there is something useful in there for this situation.


Solution

  • I was able to piece it together from stholzm's suggestion above.

    In the documentation for location, there are functions for Hostname and Port that can be used to piece together the base url. The location can be obtained via the location function that takes in a window instance.

    In the end, my code looks like

    enter image description here