How to catch user leaving a page and cancelling it

后端 未结 3 1278
萌比男神i
萌比男神i 2020-12-31 23:19

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\",

3条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-31 23:49

    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
                        }
                    }
                }
            });
        }
    

提交回复
热议问题