GWT WindowClosingHandler也在浏览器刷新 [英] GWT WindowClosingHandler firing on Browser refresh too

查看:143
本文介绍了GWT WindowClosingHandler也在浏览器刷新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我遇到一个问题,下面我写的代码检测浏览器的关闭事件使用户注销

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?");
    }
});

是的,我通过
GWT检测CloseHandler中的浏览器刷新

但我没有发现任何积极的结果。

But I didn't find any positive results there.

按照GWT Window.Closin gEvent class api:

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?

推荐答案

无法知道是否正在调用 Window.ClosingEvent 来刷新或关闭浏览器。但是,如果您的问题只是检测浏览器是否已关闭,您可以使用会话cookie。

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.

这是一个可以帮助您的实用程序类。只需在 onModuleLoad 中调用下面的行来测试。

Here is one utility class that can help you. Just call the lines below in your onModuleLoad to test.

测试行

@Override
public void onModuleLoad() {
    if (BrowserCloseDetector.get().wasClosed()) {
        GWT.log("Browser was closed.");
    }
    else {
        GWT.log("Refreshing or returning from another page.");
    }
}

实用工具类

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

这篇关于GWT WindowClosingHandler也在浏览器刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆