How to execute method on window close?

Im trying to execute code that updates my DB whenever a user closes out of the browser tab/window. Is there any way of doing this?

This is only really possible with javascript. In Javascript, you can listen to the beforeunload event and [invoke a server method]
(https://vaadin.com/tutorials/calling-java-from-javascript) that will do whatever you’ll want to do.

{project-root}/frontend/js/notifyServerBeforeUnload.js

window.notifyServerBeforeUnload = function(element){
    window.addEventListener('beforeunload', function (e) {
		element.$server.beforeUnload();
	}
}

TestView

@JsModule("./js/notifyServerBeforeUnload.js") // load js function
public TestView extends VerticalLayout {
    private static final Logger LOGGER = LogManager.getLogger(TestView.class);
	
	public TestView() {
		// execute the js function and pass this element for the js to be able to call back
		UI.getCurrent().getPage().executeJs("notifyServerAtUnload($0)", getElement());
	}
	
	@ClientCallable
	public void beforeUnload(){
		LOGGER.info("User wants to close or refresh the page.");
		// TODO: implement DB updates here
	}
}

Please note that the beforeunload event not only is triggered when closing the tab/window but also when refreshing the page. I believe that [you can’t know which one caused it to trigger]
(https://stackoverflow.com/q/11453741/3441504).
I also want to mention that [Leif Åstrand has objected]
(https://vaadin.com/forum/thread/17523194/17742954) to using the beforeunload event because this event could in addition be triggered in other seldom cases like when starting a download. However, this is not triggered for me when I use the [FileDownloadWrapper Add-on]
(https://vaadin.com/directory/component/file-download-wrapper/api/org/vaadin/olli/FileDownloadWrapper.html) for download buttons instead of using Anchor download links.

Thankyou for your help Kasper!

I just found a scenario in which this method fails, if the user moves on to a different tab and closes the tab with the vaadin window on it, the beforeUnload method will not run.

*Also, the beforeUnload method will not trigger whenever refreshing the page on firefox (which is good), however it will still trigger on chrome