Best way to detect browser closing/navigation to other page and do logout

前端 未结 4 938
夕颜
夕颜 2021-01-02 13:52

I am writing an application in GWT and I need to detect when a user navigates away from my application or when he closes the browser window (onUnload event) and do a logout

4条回答
  •  醉话见心
    2021-01-02 14:12

    The way to do that is to use the Window.addWindowClosingHandler like @Carnell and @BillLyons said. But I use an additional technique to detect if the browser has been closed or if the page is being visited again (by refresh or back navigation).

    Following there's an utility class that can help you. Just call the lines below in your onModuleLoad to test.

    The use example:

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

提交回复
热议问题