Javascript – Vaadin onbeforeunload event

Vaadin onbeforeunload event… here is a solution to the problem.

Vaadin onbeforeunload event

Are there out-of-the-box Vaadin 10 (and later) events similar to window.onbeforeunload in JavaScript?
I’ve tried using onDetach() or beforeLeave(), but it only works inside the UI and it doesn’t work when the user reloads the page or closes it.

Solution

You can use The method described in https://vaadin.com/forum/thread/17523194/unsaved-changes-detect-page-exit-or-reload This has been proposed in the comments.

In the meantime, I urge you to be extra careful with the beforeunload events, as in some cases they can be triggered even if the user doesn’t actually leave the page.

The most common scenario is when the user clicks a link to start the download. In this case, the browser fires the event as soon as the user clicks the link. Later, when the browser receives the response header, it discovers that this is a download and not a new HTML page to display. The end result is that beforeunload has been triggered, but the previous page is still running.

If you want to use that event for cleanup, the best approach today is probably to use the unload event in conjunction with the unload event and then use the new Beacon API to notify the server that the user has actually navigated. Integrating it into a Vaadin app requires a little more JavaScript, but the good thing about it is that it actually works.

Related Problems and Solutions