Search code examples
elmurl-parsing

Parsing query string inside fragment with Elm


For reasons I need to parse something which looks is formatted as a query string (i.e. key=value&another_key=another_value), but which is in the fragment of a URL, e.g:

http://example.com/callback#id_token=my_long_jwt&state=some_state

If the # was a ?, then it would be easy using <?>, but I can't figure out how (or if) I can use Url.Parser.Query when it's in a fragment.


I can get the fragment as a String:

import Url.Parser as Parser
import Url.Parser exposing ((</>))

type Route = Callback String | NotFound

route : Parser.Parser (Route -> a) a
route = Parser.map Callback (Parser.s "callback" </> fragmentWithDefault )

fragmentWithDefault : Parser.Parser (String -> a) a
fragmentWithDefault = Parser.fragment <| Maybe.withDefault "no_fragment"

toRoute : Url.Url -> Route
toRoute url = Maybe.withDefault NotFound (Url.Parser.parse route url)

But there is no API in Url.Parser.Query which runs a Url.Parser.Query.Parser against which I can run the String in Callback.


Solution

  • The Url parser just treats Url fragment as a String but you can replace # with ? before parsing:

    Maybe.withDefault url <| Url.fromString <| String.replace '#' '?' <| Url.toString url
    

    then you will get your fragment in query part so you can parse it normally.