GWT handle back, refresh, close buttons

2.4k views Asked by At

I'm trying to run some RPC calls when the user closes the window, refreshes it or clicks the back button but just for one single page. I found a post talking about handling but the solution is not working well, missing back button handler (not working) and always is for all page on the web, I can't find something for remove handler if you leave from page

    Window.addWindowClosingHandler(new Window.ClosingHandler() {

                @Override
                public void onWindowClosing(ClosingEvent event) {
                    event.setMessage("You sure?");
                }
            });

    Window.addCloseHandler(new CloseHandler<Window>() {

                @Override
                public void onClose(CloseEvent<Window> event) {

                    // Execute code when window closes!
                System.out.println("ble ! ");

                }
            });

Framework: GWT 2.4 with mvp4g.
Browsers: FF and Chrome.

2

There are 2 answers

1
Igor Klimer On

You need to remove the handler when you leave the page and then re-add it when you enter the page again. You have the "add" side covered with the above code, you are missing the "remove" part. You do that by using the HandlerRegistration object that is returned from the add*Handler methods. When you want to remove the registered handler, you just call the HandlerRegistration.removeHandler() method:

HandlerRegistration windowClosingHandler = Window.addWindowClosingHandler(new ClosingHandler() {
    @Override
    public void onWindowClosing(ClosingEvent event) {
        // Handle window closing
    }
});
// From now on the CloseHandler will be fired

// ...
// Somewhere else:
windowClosingHandler.removeHandler();
// From now on the CloseHandler won't be fired
0
gfelmer On

Because i use mvp4g framework i found a solution there , you need to extends your presenter with CyclePresenter and override onLoad and onUnload methods. These methods fire when view is load/unload from DOM, i tested and work for all cases, f5, back button, close browser/tab, go other web and call others events. Now i cant put some code there.