GWT detect browser refresh in CloseHandler

一曲冷凌霜 提交于 2019-11-30 23:46:27

There is no way to differentiate the 'close' from 'refresh'. But, you can set a cookie that holds the last CloseHandler call time and check, when loading the module, if this time is old enough to clean the information before showing the page.

You can do that with the folowing utility class (BrowserCloseDetector). Here is an example using it on the onModuleLoad.

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

Have you tried

<BODY onUnload = "scriptname">

in your gwt hosting/launching html file?

I am thinking that if you defined a map "hash" (i.e. a javascript pseudo hash) in the hosting file and then accessed the "hash" in GWT through Dictionary class, you could update values in that hash as the user progresses through the gwt app. Which means, your programming style would require you to log milestones on the user's progress onto this map.

When the user closes the browser page, the onunload script of the launching html page would be triggered. That script would access the map to figure out what needs to be updated to the server, or what other url to launch.

I am intereted too if someone got a solution (GWT/java side only). Maybe we can do it with HistoryListerner ? 1-set a flag for your current viewing page. 2-when ClosingHandler event, launch a "timeout" on server-side (for example 10s) 3-if during this time your got a massage from HistoryListerner with the same last flag so it was just a refresh. of disconnect if timer is over...

Is not a good solution but I think it is easy to do... If someone have a better one...

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!