Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...