GWT WindowClosingHandler firing on Browser refresh too

后端 未结 1 1652
天涯浪人
天涯浪人 2020-12-10 09:40

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 unfort

相关标签:
1条回答
  • 2020-12-10 10:26

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题