Search code examples
f#browser-historywebsharper

Writing handlers for JS.Window.Onpopstate in Websharper


I'm trying to get proper back-button support in my WebSharper-app. I can put stuff in history just fine:

type MyRecord = { foo: int; bar: string } 
JS.Window.History.PushState({foo=10; bar="hello"}, "", "mysuffix")

I was hoping to add a corresponding handler for onpopstate by doing something like this:

JS.Window.Onpopstate <- (fun e -> Javascript.Console.Info e.State.bar)

Unfortunately, this event has type Js.Window.Onpopstate : Dom.Event -> Unit and Dom.Event doesn't have a field State for getting back the state, even though the corresponding "real" Javascript event does.

How do I access state stored with PushState in the Onpopstate handler?


Solution

  • You can access arbitrary fields from objects using the dynamic operator ?:

    JS.Window.Onpopstate <- (fun e ->
        Console.Info e?state.bar
    )
    

    Note however that you still need to use [<Inline>] to call an arbitrary method.