Search code examples
elmlocation-href

How can I get window.location.href in Elm?


I have an index.html which contains my Elm app. The Elm app uses various GETs to an API served by the same server as the one that serves the index.html.

Rather than hardcode the URLs in my Elm code for the GETs, e.g.:

url =
    "http://localhost:8080/api/tasks"

is there a function which returns the value of window.location.href?

I'd like to do something like:

url =
    getHref() ++ "/api/tasks"

In this way, if I move my server to somewhere else I will not need to update all the urls in my Elm code.


Solution

  • There is elm-history package with the location function for this, but it's deprecated and doesn't exist for 0.18 version.

    Then you might want to use elm-navigation package and explicitly store the current location in your model.

    Please have a look at this example. A program with navigation can be created via:

    Navigation.program UrlChange
        { init = init
        , view = view
        , update = update
        , subscriptions = (\_ -> Sub.none)
        }
    

    UrlChange here is a type of message, which triggers on every url change, so you can process it and set the current location:

    update : Msg -> Model -> ( Model, Cmd Msg )
    update msg model =
        case msg of
            UrlChange location ->
                ( { model | location = location }
                , Cmd.none
                )
    

    And then purely get the location.href wherever the model is accessible.

    In the provided application, this place is view: viewLocation model.location

    In your application, it's, for example, something like this:

    url model =
        model.location.href ++ "/api/tasks"