flow icon indicating copy to clipboard operation
flow copied to clipboard

UI BeforeLeave is called upon page load

Open stefanuebe opened this issue 5 months ago • 0 comments

Description of the bug

It appears, that a UI before leave listener is called upon page load before the first page has been even shown. This may lead to unwanted side effects, if the developer is not aware of this unintuitive behavior.

Expected behavior

Before leave should only be called, when the user navigates away from a real page.

Minimal reproducible example

  1. Use the code below in a new Vaadin app
  2. Open your browser and navigate to view A, e.g. http://localhost:8080/viewa
  3. Check the server console, it should have printed UI before leave on PAGE_LOAD (the view before leave listeners are not invoked)
  4. Optionally switch between the views using the router links. The console prints more before leave messages, which are correct at this point.
@SpringComponent
public class VaadinInitializer implements VaadinServiceInitListener {
    @Override
    public void serviceInit(ServiceInitEvent event) {
        event.getSource().addUIInitListener(uiEvent -> {
            uiEvent.getUI().addBeforeLeaveListener(beforeLeaveEvent -> System.out.println("UI before leave on " + beforeLeaveEvent.getTrigger()));

        });
    }
}

@Route
public class ViewA extends Div implements BeforeLeaveObserver {

    public ViewA() {
        add(new RouterLink("Go to B", ViewB.class));
    }

    @Override
    public void beforeLeave(BeforeLeaveEvent event) {
        System.out.println("ViewA before leave on " + event.getTrigger());
    }
}

@Route
public class ViewB extends Div implements BeforeLeaveObserver {

    public ViewB() {
        add(new RouterLink("Go to A", ViewA.class));
    }

    @Override
    public void beforeLeave(BeforeLeaveEvent event) {
        System.out.println("ViewB before leave on " + event.getTrigger());
    }
}

Versions

  • Vaadin / Flow version: 24.8.0.alpha7
  • Java version: 17

stefanuebe avatar May 21 '25 06:05 stefanuebe