[英]Detect any user interaction
I have a web application and when the user is logged in, I would like to display a popup after some time if the user doesn't do anything to warn him that he will be logged out soon.我有一个 Web 应用程序,当用户登录时,如果用户没有做任何事情来警告他很快就会注销,我想在一段时间后显示一个弹出窗口。
So I used intervals and I reset it each time the user interacts :所以我使用了间隔,并在每次用户交互时重置它:
$(this).mousedown(function () {
reset();
});
$(this).mousemove(function () {
reset();
});
$(this).scroll(function () {
reset();
});
$(this).mouseup(function () {
reset();
});
$(this).click(function () {
reset();
});
$(this).keypress(function () {
reset();
});
But in some case, the timer is not reset and the popup shows up when the user is still using the application, for example when scrolling in a div.但在某些情况下,计时器不会重置,并且当用户仍在使用应用程序时会显示弹出窗口,例如在 div 中滚动时。
Do I have to add my reset function to all possible events in my application or is there a simpler way to detect any interaction ?我是否必须将我的重置功能添加到我的应用程序中所有可能的事件中,还是有更简单的方法来检测任何交互?
To cover all machine types (PC, Tablet/phone (touch device), PC without mouse..)涵盖所有机器类型(PC、平板电脑/手机(触摸设备)、不带鼠标的 PC..)
on the body tag add a reset for these events:在 body 标签上为这些事件添加一个重置:
That should cover any activity, I believe我相信这应该涵盖任何活动
I agree with the answer above but in my case I don't have JQuery.我同意上面的答案,但就我而言,我没有 JQuery。
I also listen for touchstart and click.我也听 touchstart 和 click。 In addition I use debounce to wait for all interaction to stop for one seccond.此外,我使用 debounce 来等待所有交互停止一秒。
import _ from 'lodash';
let ListenForInteraction = function () {
let lastId = Date.now();
let callbacks = {};
this.onInteraction = (callback) => {
lastId++;
callbacks[++lastId] = callback;
return
};
this.handleInteraction = _.debounce(() => {
console.log('Interaction')
for (let i in callbacks) {
if (typeof callbacks[i] === 'function') {
callbacks[i]();
} else {
delete callbacks[i];
}
}
}, 1000);
document.body.addEventListener('mousemove', this.handleInteraction);
document.body.addEventListener('scroll', this.handleInteraction);
document.body.addEventListener('keydown', this.handleInteraction);
document.body.addEventListener('click', this.handleInteraction);
document.body.addEventListener('touchstart', this.handleInteraction);
};
let listenForInteraction = new ListenForInteraction();
export default listenForInteraction;
//USAGE
listenForInteraction.onInteraction(() => {
localStorage.last_interaction = Date.now();
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.