tags:

views:

383

answers:

3

Hello there,

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

+3  A: 

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

Window.addWindowClosingHandler(handler)

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

Isac
I don't think that method exists? Do you mean addWindowCloseListener?
John Weldon
addWindowCloseListener is deprecated since GWT 1.6. You should use Window.addCloseHandler(handler) or Window.addClosingHandler(handler) instead.
Isac
Isac, instead of making a comment on your answer, you can just edit it to mention the current function.
aem
This won't do what the question asks, because addCloseHandler passes you a CloseEvent, which happens when it's too late to close the window. addWindowClosingHandler lets you do what the question asks. See http://google-web-toolkit.googlecode.com/svn/javadoc/2.0/com/google/gwt/user/client/Window.ClosingEvent.html and http://google-web-toolkit.googlecode.com/svn/javadoc/2.0/com/google/gwt/event/logical/shared/CloseEvent.html
aem
+3  A: 

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.

aem
This works great! Thanks!
stuff22
A: 

Could anybody tell me why this piece of code doesn't work in Opera (10.62) but works fine in FireFox (3.6.10) and IE (7).

Gary Glover