[英]How to log user leaving and returning to page with Ajax
我正在编写在线考试,我想知道用户何时离开考试页面以及何时再次返回。 我有
if(document.hasFocus()==false){
$.ajax({
type: "POST",
url: 'submission.php',
data: {status: 'Absent'},
success: function(data)
{ alert("Hey, you!"); }
});
}
PHP 将状态更新、时间和用户 Ip 放入数据库。 但我想在他们返回考试时记录下来,以便计算缺勤时长。 我想出的最好的方法是
<script>
setInterval(checkFocus, 2000); // updates DB and issues alert every 2 seconds
function checkFocus()
{
if(document.hasFocus()){
$.ajax({
type: "POST",
url: 'submission.php',
data: {status: 'Present'},
success: function(data)
{ alert("Good luck in the exam!"); }
});
}
if(document.hasFocus()==false){
$.ajax({
type: "POST",
url: 'submission.php',
data: {status: 'Absent'},
success: function(data)
{ alert("Hey, you!"); }
});
}
}
</script>
我会删除警报:) 但即使用户停留在页面上,此代码也会每 2 秒更新一次数据库。 我只是想不出当用户离开页面并返回时只更新数据库的逻辑/排序。
关于调整您的解决方案,您需要跟踪以前的 state,然后仅在它与当前 state 之间存在差异时才采取行动:
const checkFocus = (() => {
let hadFocus = null;
return () => {
const hasFocus = document.hasFocus();
if(hadFocus == hasFocus) return;
hadFocus = hasFocus;
if(hasFocus) {
// Do something when page focus gained
}
else {
// Do something when page focus lost
}
};
})();
setInterval(checkFocus, 2000);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.