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]
( that will do whatever you’ll want to do.


window.notifyServerBeforeUnload = function(element){
    window.addEventListener('beforeunload', function (e) {


@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());
	public void beforeUnload(){"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]
I also want to mention that [Leif Åstrand has objected]
( 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]
( 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