Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

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 ?

like image 698
user3544117 Avatar asked Sep 30 '14 13:09

user3544117


2 Answers

To cover all machine types (PC, Tablet/phone (touch device), PC without mouse..)

on the body tag add a reset for these events:

  • onMouseOver
  • onscroll
  • onkeydown

That should cover any activity, I believe

like image 133
user2808054 Avatar answered Oct 13 '22 05:10

user2808054


I agree with the answer above but in my case I don't have JQuery.

I also listen for touchstart and click. In addition I use debounce to wait for all interaction to stop for one seccond.

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();
})
like image 20
tanner burton Avatar answered Oct 13 '22 07:10

tanner burton