如何区分页面刷新和关闭页面 [英] How to tell the difference between a page refresh and closing a page

查看:134
本文介绍了如何区分页面刷新和关闭页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网络应用程序游戏,而在游戏中我想拥有它,所以如果用户关闭页面或他们的浏览器,它会自动注销它们。我尝试使用附加到窗口的onbeforeunload事件:

I have a web app game and while in the game I want to have it so if a user closes the page or their browser, it will automatically log them out. I tried using the onbeforeunload event attached to the window:

window.onbeforeunload = function() {
    // perform logout functions here
}

问题是,如果用户刷新,也会触发页。有没有办法可以检测用户是否完全关闭整个页面,或者只是刷新它?

The problem is, that will also fire if the user refreshes the page. Is there a way I could detect whether or not the user is completely closing the whole page, or just refreshing it?

推荐答案

不是可检测的差异。要自动注销用户,您应该在存储登录或会话信息的cookie上设置到期日期。因此,如果您将其设置为1小时,那么在该时间之后用户将基本上被注销,因为cookie将被销毁。如果您想在他们仍然与网站交互时推迟此自动注销,您可以在每次执行某种操作(单击链接,激活AJAX调用等)时重置cookie的过期。这意味着他们将在1小时不活动后退出,而不是登录后1小时,这听起来更像你想要的。

There is not a detectable difference. To automatically logout a user, you should set an expiration on your cookie storing the login or session information. So if you set it for 1 hour, the user would essentially be logged out after that time since the cookie would be destroyed. If you wanted to postpone this auto logout while they are still interacting with the site, you could reset the expiration of the cookie every time they perform some sort of action (clicking a link, activating an AJAX call, etc). That would mean that they'd be logged out after 1 hour of inactivity as opposed to just 1 hour from login, which sounds more like what you want.

如果你设置cookie的到期时间为0,然后它会在会话结束后到期。这通常发生在用户完全退出浏览器时。这也是另一种选择。

If you set the cookie's expiration to 0, then it will expire it after the session ends. That usually occurs when the user quits their browser entirely. That's another option as well.

这篇关于如何区分页面刷新和关闭页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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