Warning modal when unsaved form in LiveView is closed.

Hi, I’m looking for a solution to the following problem: When I’m on a page with an unsaved LiveView form and exit it via one of the numerous options, I want a modal or an alert to pop up informing me that I’m about to discard unsaved changes. With two buttons, I would like to provide the option of not leaving the page to continue editing the form or leaving the form and discarding the changes.

I have already found other posts with very similar questions here in the forum, such as this, however these approaches are always based on JavaScript “beforeunload” or an assign on close button.
However, in my case I have a whole sidebar with many buttons that close the form, also I want to add this warning on all my LiveView form pages.

Is there any way to use Phoenix’s built-in functions to react to a form leaving before it actually closes?
I appreciate any advice that gets me a little closer to my solution, thanks!

What about a flag that is set when any input is changed: phx-change="set_flag"

And then reset it when the form is saved.

Then make every outgoing link check_flag when clicked.

<%= link "Go somewhere else", to: "#", phx_click: "check_flag" %>
def handle_event("check_flag", _params, socket) do
  if socket.assigns.set_flag do
    # do the things
  else
    {:noreply, push_redirect(socket, to: "/some_route")}
  end
end

Thank you for your answer, I have also thought about a similar approach, but such a flag in the assigns only partially solves my problem.
For example, if I now use the browser navigation to exit the form, I can’t query the flag this way. The same applies to the layout links, e.g. in my sidebar, which are outside my LiveView.

I am rather looking for a possibility to react to the leaving of the LiveView with the help of LiveView before it has really been left.

In that case track the flag on the client side with JavaScript. Bind a js function to phx-change and then reset when form is submitted

<input type=“text” phx-change=“setInputChanged()” … />

...