1

I've got an application built using the SAFE stack where active clients have corresponding objects on the Server side. When a user closes their browser window, I would like a message to be sent to the server to delete that object.

I'm trying to use the "onunload" event like this:


module WindowEvents =
    let unloadSub _ =
        let setUnloadEvent dispatch = 
            Browser.Dom.window.onunload <- (fun _ -> dispatch CloseEvent)
        Cmd.ofSub setUnloadEvent

and I add that to the subscriptions:

Program.mkProgram Model.init Model.update View.render
|> Program.withSubscription WindowEvents.unloadSub

The message is handled in the usual Elmish way and is forwarded on to the Server via the api. However, I find that the message only rarely arrives server-side. Is there something I can do to make this more reliable? Or is there an alternative approach that would be better?

JamesFaix
  • 8,050
  • 9
  • 37
  • 73
  • 1
    try using the onbeforeunload event instead of onunload? This might be more reliable. – onemorecupofcoffee Apr 12 '20 at 06:37
  • Yes, I switched to that after posting this, but it only made a very slight difference. From reading this answer https://stackoverflow.com/a/52412486/1353612 I think maybe there's no good way of handling an async request that will be sure to execute properly. This is not something I'm too familiar with, though. Is Navigator.SendBeacon implemented anywhere in Fable? – Andrew Willshire Apr 12 '20 at 08:56
  • I see in [github](https://github.com/fable-compiler/fable-browser/blob/master/src/Navigator/Browser.Navigator.fs) it is marked as TODO – onemorecupofcoffee Apr 12 '20 at 09:47

0 Answers0