Access Binder changed state in Javascript for dirty form check

Hey,

I’ve been trying to implement a dirty form check (ask the user if he really wants to leave the page if the form is dirty) which also works for reload and tab/browser-closing. For this to work I need to add a listener to the javscript beforeunload event afaik.
In short i need a javscript snippet like this:

window.addEventListener('beforeunload', (event) => {
  if (formChanged) {
    event.returnValue = 'You have unfinished changes! Do you really want to leave?';
  }
});

My question is now: how do i get the formChanged from the binder in java into my javscript code?

Couldn’t you use a BeforeLeaveObserver on the view?

Sadly that’s not triggered for all mentioned cases, see the old comment from Leif https://github.com/vaadin/flow/issues/8400#issuecomment-632507543

For the browser close I use the UnloadObserver from Superfields https://vaadin.com/directory/component/superfields

We already implemented this and that’s only fired if it’s leaving due to “in-app” navigation.

I know that it’s not perfectly, but your it’s your customers wish to implement this even if it’s sometimes not fired.

I saw the Beacon Stuff mentioned there in https://cookbook.vaadin.com/notice-closed but I dont fully get how to use this to interrupt the close

thanks, I’ll take a look at their code

Hey Simon, I took a look at this and the documentation of the library is not really good I have to say. Can you explan me how to use this only if the binder has changes?

I thought this was no longer necessary since the new Beacon API was in place. Was I mistaken?

It depends. It clears up resources, but it won’t notify the binder for the leave event that is needed here.

good point. I am using the Guava event bus, so my main concern was removing stale listeners. But out of the box implementation of unload observer for the “you have not saved you will loose your changes” would be very nice.