Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

events - GWT WindowClosingHandler firing on Browser refresh too

Here I am facing an issue with the code below I wrote to detect the browser's close event to make user logged out from website.

But unfortunately this event fires on Refresh too :(.

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

Yes, I gone through GWT detect browser refresh in CloseHandler

But I didn't find any positive results there.

As per GWT Window.ClosingEvent class api:

Fired just before the browser window closes or navigates to a different site.

But I still have hope that we can detect browser refresh.

Can any one give a hint regarding this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is imposible to know if the Window.ClosingEvent is being called to refresh or to close the browser. But, if your problem is only to detect if the browser has been closed, you can use session cookies.

Here is one utility class that can help you. Just call the lines below in your onModuleLoad to test.

The test lines:

@Override
public void onModuleLoad() {
    if (BrowserCloseDetector.get().wasClosed()) {
        GWT.log("Browser was closed.");
    }
    else {
        GWT.log("Refreshing or returning from another page.");
    }
}

The utility class:

import com.google.gwt.user.client.Cookies;
import com.google.gwt.user.client.Window;

public class BrowserCloseDetector {
    private static final String COOKIE = "detector";
    private static BrowserCloseDetector instance;

    private BrowserCloseDetector() {
        Window.addWindowClosingHandler(new Window.ClosingHandler() {
            public void onWindowClosing(Window.ClosingEvent closingEvent) {
                Cookies.setCookie(COOKIE, "");
            }
        });
    }

    public static BrowserCloseDetector get() {
        return (instance == null) ? instance = new BrowserCloseDetector() : instance;
    }

    public boolean wasClosed() {
        return Cookies.getCookie(COOKIE) == null;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...