How to detect when the user navigates away from the app window?

Typically, when I’m editing something in a native app — such as an email — and I navigate away from the app to another app, or to the main screen, I get a notification that says “Saved”.

I need to do something similar in my Elm app.

Html.Events.onFocus and Html.Events.onBlur (and the elm-ui equivalents) don’t seem to do what I want — in fact they don’t seem to do anything — and Html.Events.on “focusin” and Html.Events.on “focusout” seem to have strange behaviour — see How to detect focus and blur

Browser.Events.onVisibilityChange detects when the app window is gone from sight, but what about when someone simply clicks on another window when the app is on a desktop? How can I detect that kind of ‘navigating away’?

It sounds like you are looking for the blur event on window.

You can add an event listener for it with JavaScript and call a port in it.

2 Likes

Ah :slightly_smiling_face: blur event on window ! That’s almost certainly it. I was conflating element and window!
Thank you, Simon @lydell