To achieve this functionality, you can utilize the Window.addWindowClosingHandler
method as suggested by @Carnell and @BillLyons. In addition to this, I implement an extra technique to identify whether the browser has been closed or if the page is being revisited (through refresh or back navigation).
Below is a utility class that can assist you in this process. Simply add the following lines in your onModuleLoad
function to test it out.
Example of how to use it:
@Override
public void onModuleLoad() {
if (BrowserCloseDetector.get().wasClosed()) {
GWT.log("Browser has been closed.");
}
else {
GWT.log("Page is being refreshed or navigated back to.");
}
}
The utility class code snippet:
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;
}
}