How to catch a user by leaving the page and canceling it

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

I know how to create a dialbox. :)

The question is, how can I catch an event when a user leaves the page and how to cancel it?

Daniel

+6
gwt
source share
3 answers

Call Window.addWindowClosingHandler and pass it a callback that calls setMessage in Window.ClosingEvent, for example:

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

(I added links to GWT 2.0 docs, changing 2.0 to 1.6 in these URLs to see GWT 1.6 / 1.7 docs.)

Please note that for this you do not need / do not create a dialog box yourself.

+16
source share

You need to create a CloseHandler and register it in the window:

Window.addWindowClosingHandler(handler)

EDIT: Fixed method name. See Comment and Reply to Comment.

+4
source share

Call the method below in 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 } } } }); } 
+2
source share

All Articles