当用户登录和注销网站时,我试图将用户活动记录在我的数据库中。这很好,但当他们通过选项卡或浏览器关闭页面时,无法运行注销查询,因此根据记录,用户从未注销过网站。
方法1:我尝试过onbeforeunload
,但在页面关闭之前似乎不会触发。
方法2:我会尝试使用发送到php的ajax keepalive令牌的方法,但这需要每1分钟运行一次,可能会导致高流量负载。
方法3:我希望一个替代方案是将session.gc.maxlifetime
设置为1分钟,并通过destroy会话回调向注销查询添加一个调用。
哪种方法是最好的,或者有更好的方法来实现这一点吗?
有没有一种方法可以在php销毁会话或php垃圾收集发生之前触发自定义函数(查询)?
更新
我听取了所有人的建议,决定尝试"方法1"。到目前为止,这是我的尝试,但它仍然没有完美地工作:
var isClosePage = true;
//detect f5 and backspace page navigation
$(document).on('keypress', function(e)
{
if (e.keyCode == 116)
{
alert('f5');
isClosePage = false;
}
if (e.keyCode == 8)
{
alert('backspace');
isClosePage = false;
}
});
//detect back and forward buttons
$(window).bind('statechange',function()
{
alert('back');
isClosePage = false;
});
//detect page button press
$('html').on('mouseenter', function()
{
console.log('mouse has enetered!');
isClosePage = false;
});
//detect browser buttons press
$('html').on('mouseleave', function()
{
console.log('mouse has left!');
isClosePage = true;
});
//make ajax call (logout) to server if above events not triggered
$(window).on('beforeunload', function(e)
{
if(isClosePage)
{
$.ajax(
{
url:'php/function/active-user.php?logout=ajax',
dataType: 'jsonp',
crossDomain: true,
async: false
});
//return 'some default message';
}
else
{
isClosePage = true;
}
});
有人能建议我如何改进这项工作吗?
当你谈到方法1时,你是在客户端进行的,对吧
接口是window.onbeforeunload
,这是一个使用示例:
window.onbeforeunload = function(e) {
// call server script to log the user activity to database ...
};
事件window.onbeforeunload
在页面卸载之前触发(选项卡/窗口/浏览器关闭)。
我想稍微扩展一下MarcoS的答案。window.onbeforeunload
应该可以工作,但这不是设置事件处理程序的首选方式。由于这是一个属性,附加到此事件的其他脚本将覆盖您的侦听器,并且您的函数永远不会被调用。
注册此事件的首选方式如下:
window.addEventListener('beforeunload', function (evt) {
}, false);
您还可以将事件侦听器附加到unload
window.addEventListener('unload', function (evt) {
}, false);
希望这能帮助