How to catch user leaving a page and cancelling it

2020-02-26 10:52发布

When a user leaves the GWT app, I would like to open a confirm dialog and offer them the choice to stay, i.e. Confirm("are you sure you want to leave this page", "yes", "no").

I know how to build the dialbox. :)

The question is, how to I catch the event of a user leaving the page and how to I cancel it?

Daniel

标签: gwt
3条回答
Anthone
2楼-- · 2020-02-26 11:14

Call the method below in the onModuleLoad().

 private void setupHistory() {
        final String initToken = History.getToken();
        if (initToken.length() == 0) {
            History.newItem("main");
        }

        // Add history listener
        HandlerRegistration historyHandlerRegistration = History.addValueChangeHandler(new ValueChangeHandler() {
            @Override
            public void onValueChange(ValueChangeEvent event) {
                String token = event.getValue();
                if (initToken.equals(token)) {
                    History.newItem(initToken);
                }
            }
        });

        // Now that we've setup our listener, fire the initial history state.
        History.fireCurrentHistoryState();

        Window.addWindowClosingHandler(new ClosingHandler() {
            boolean reloading = false;

            @Override
            public void onWindowClosing(ClosingEvent event) {
                if (!reloading) {
                    String userAgent = Window.Navigator.getUserAgent();
                    if (userAgent.contains("MSIE")) {
                        if (!Window.confirm("Do you really want to exit?")) {
                            reloading = true;
                            Window.Location.reload(); // For IE
                        }
                    }
                    else {
                        event.setMessage("My App"); // For other browser
                    }
                }
            }
        });
    }
查看更多
够拽才男人
3楼-- · 2020-02-26 11:16

You have to create a CloseHandler and register it on the Window:

Window.addWindowClosingHandler(handler)

EDIT: Fixed method name. See aem comment and answer.

查看更多
我命由我不由天
4楼-- · 2020-02-26 11:21

Call Window.addWindowClosingHandler, and pass it a callback that calls setMessage on the Window.ClosingEvent, like so:

Window.addWindowClosingHandler(new Window.ClosingHandler() {
      public void onWindowClosing(Window.ClosingEvent closingEvent) {
        closingEvent.setMessage("Do you really want to leave the page?");
      }
    });

(I've put in links to the GWT 2.0 docs; change the 2.0 to 1.6 in those URLs to see the GWT 1.6/1.7 docs.)

Note that doing it this way, you don't have to/don't get to create the dialog box yourself.

查看更多
登录 后发表回答