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

查看:16
本文介绍了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.

但不幸的是,这个事件也会在 Refresh 上触发 :(.

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.ClosingEvent 类 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天全站免登陆