How to prevent navigation?

I understand that I can implement a BeforeLeaveObserver but how can I cancel the navigation?

Or is there a way to have something like a BeforeNavigationObserver to prevent the navigation?

Hi Simon,

Could you come up a valid use case for preventing the navigation? if that cannot be achieved with the current flow implementation, we could open an enhancement ticket for the product.

BR.

Hi Simon

Yes this is possible with a BeforeLeaveObserver. You can call the postpone() method on the BeforeLeaveEvent to achieve this.

Please note that the beforeLeave method is not triggered if you close the browser or the browser-tab, or when you navigate by entering a new URL manually. If you need to catch those types of leaving too, have a look at [this thread]
(https://vaadin.com/forum/thread/17523194/unsaved-changes-detect-page-exit-or-reload)

@Override
public void beforeLeave(BeforeLeaveEvent event) {
	// only prevent if certain condition is met. In my example I prevent navigation if binder has changes.
	if(binder.hasChanges()){
	
		// prevents navigation
		BeforeLeaveEvent.ContinueNavigationAction action = event.postpone();

		// after you prevented the navigation, you are still able to proceed with the navigation, by using action.proceed();
		// it is good practice IMO to give the user the choice to navigate away anyway, if they wish so. 
		ConfirmDialog dialog = new ConfirmDialog(
				"Unsaved Changes",
				"You have unsaved changes. Are you sure you want to leave this page anyway?",
				"yes", confirmEvent -> {
					// do the navigation anyway
					action.proceed();
				},
				"no", cancelEvent -> {
					// navigation was already prevented with event.postpone() so nothing has to be done here
				}
		);
		dialog.open();
	}
}

Ok this works.

But the URL is wrong because it is already the URL of the target route.
Is there a way to reset that?

That is an known issue currently, https://github.com/vaadin/flow/issues/3619 and you can find a workaround in the ticket https://github.com/vaadin/flow/issues/3619#issuecomment-472851575