简体   繁体   中英

How can I show a confirm dialog with Vaadin 23 when the user clicks on back button?

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

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...

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.

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM