0

how can I show a dialog to stay or leave the current page with Vaadin 23, when a user clicks back button on browser?

Regards

3 Answers3

2

It depends what you wish to achieve.

See this older discussion: Vaadin onbeforeunload event

Generally: use the onBeforeUnload javascript even for this https://www.w3schools.com/tags/ev_onbeforeunload.asp

This is executed when the user would go away from your vaadin app, but not when using the back button inside your vaadin app.

For these you can use the navigation lifecycle events as documented here https://vaadin.com/docs/latest/routing/lifecycle

Not sure if it also catches, when a user leaves your app...

André Schild
  • 4,592
  • 5
  • 28
  • 42
1

Assuming you mean, that is it possible to prevent the navigation happening, you simply can't do that. If disabling back button is important for you, the only way is to enforce your users to use the application via desktop shortcut which starts the app using --app paramater (if using Chrome). This is not a limitation in Vaadin, but a general restriction in browser behavior.

Tatu Lund
  • 9,949
  • 1
  • 12
  • 26
  • You can't absolutely prevent navigation from happening, but that wasn't the question. What you can do is add an `onbeforeunload` handler, which allows you to show a browser-native "are you sure you want to leave" prompt. – ollitietavainen Jan 16 '23 at 11:28
  • But the state will be lost. Say you have a form on the page, you can use onbeforeunload, yes. And you can do even programmatic navigation back, but your edits will be lost nevertheless. – Tatu Lund Jan 16 '23 at 12:36
-1

There is already a possibility to handle Browser Back Button Event on Vaadin (https://vaadin.com/docs/v14/flow/routing/tutorial-routing-lifecycle):


public class SignupForm extends Div implements BeforeLeaveObserver {

    @Override
    public void beforeLeave(BeforeLeaveEvent event) {

        if (this.hasChanges()) {

            ContinueNavigationAction action = event.postpone();

            ConfirmDialog.build("Are you sure you want"+
                    " to leave this page?")
                    .ifAccept(action::proceed)
                    .show();
        }
    }

    private boolean hasChanges() {
        // no-op implementation
        return true;
    }
}

This code works once but when you click on Cancel on Confirm Dialog so that you want to stay on current page and click again on Back Button on Browser, than you don't see any Confirm Dialog again... I can not understand, why...