Jquery keep Alive / Any client side interaction? - javascript

I have used a few of the jquery keepalive session plugins with out problem.
I have been asked for something a bit different.
We have some forms (built before I started here) that are fairly large and users work in them for a while. The page is never refreshed, so they click save and the session is expired and redirect to the login page.
I suggested one of these plugin, that just prompt the user a few minutes before the session expires which would make an ajax call to keep the session alive.
However, they said, will what if they dont see the prompt and miss it all together and logs them out.
They would like me to check
Has the user had any interaction with the page in the last 5 minutes.
If Yes=Ajax call to keep alive the session, and reset timer.
if No, continue to wait until we get within 2 minutes of session time out and prompt user.
They are trying to avoid the prompt.
Is there anyway with JS/Jquery to know if the page has had any client side interaction?

Rather than using a timer to check if they've had any interaction in the last 5 minutes, couldn't you just send your keepalive any time the form has changed? It would eliminate a need for a timer loop and a small payload ajax call just to keep the session alive shouldn't hurt performance at all.
If you still want to keep the timer loop, I would still recommend using the change event on your form elements. Changing the form implies they're interacting with it, and I think that satisfies their requirement.
Edit: Update to use timer
var idle = true;
function finalIdleCheck(prompt){
if(idle){
if(prompt){
alert("last warning!");
}
//Tighten the idle check time loop; may even want to go < 30s
setTimeout(finalIdleCheck, 30*1000);
} else {
//Ajax stuff to keep session alive
idle = true; //Reset idle flag
}
}
function checkIdle(){
if(idle){
//Warn them
alert("You've been idle");
setTimeout(function(){
finalIdleCheck(true);
}, 60*2*1000);
} else {
//Ajax stuff to keep session alive
idle = true; //Reset idle flag
}
}
$(document).ready(function(){
$("form input").on("change", function(){
idle = false;
}
setTimeout(idleCheck, 60*5*1000);
}

Related

How to handle inactive users and log them out in react JavaScript?

I'm working on a private site with important data, and I want to log out any user who hasn't done anything for 10min (forgot the tab open in the background as an example). How can I do that, is just running an event listener to the mouse clicks with a timer is fine, or are there other better solutions for this?
This can be achieved by JavaScript only.
Since our web app can be open in multiple tab, so its better to store last activity of user in localStorage
First lets declare events which we consider as user activity and store time of user activity in localStorage
document.addEventListener("mousemove", () =>{
localStorage.setItem('lastActvity', new Date())
});
document.addEventListener("click", () =>{
localStorage.setItem('lastActvity', new Date())
});
Next lets create interval which will be checked on every given interval.
let timeInterval = setInterval(() => {
let lastAcivity = localStorage.getItem('lastActvity')
var diffMs = Math.abs(new Date(lastAcivity) - new Date()); // milliseconds between now & last activity
var seconds = Math.floor((diffMs/1000));
var minute = Math.floor((seconds/60));
console.log(seconds +' sec and '+minute+' min since last activity')
if(minute == 10){
console.log('No activity from last 10 minutes... Logging Out')
clearInterval(timeInterval)
//code for logout or anything...
}
},1000)
event listeners for mouse movement (not clicks), and event listeners for keyboard clicks as well should do the job.
Let's say you want to log out the user after 10mins of inactivity. Simply start a timer (for 10mins) the moment user logs in, every time the user makes any mouse movement or any keyboard clicks, use the event listener to reset the timer.
If there is no activity, after 10mins, the timer should execute log out functionality.
Update :
Like the case suggested by Vishnu Bhadoriya, in that case, the idle solution should be to implement a heartbeat b/w the client and the server. Now, in this case, your mouse and keyboard listeners would send a lifeline event to the server, and the server will keep its session alive. When the lifeline event is not received by the server for more than 10mins (threshold for activity), the server can emit an event to the client which can log him out or can simple invalidate the client's auth token

Timeout does not log out if windows is locked

I have been recently working on the timeout function (used javascript - setInterval). I did test it, it worked exactly the way I want apart from one tiny detail. Whenever a logged in user sleeps the computer, the session is still active and timeout keeps counting the time. Consequently, after waking the PC up, let's say after 40 min, the timeout says e.g. -10 min and the user is still logged in. If he clicks anything or refresh the page, the service will refresh and the timeout is being restarted to the initial value like nothing happened (user is still logged in). Is there a way of making sure that the user is going to be logged out after waking the PC up?
Thanks a lot in advance!
If I understand your problem, the solution could be to call a script in ajax when the timeout has a value of 0, which will log out the user and then you could refresh the page, the all thing in javascript
Rather than using setTimeout/setInterval for you logout directly, perhaps try something like this:
var targetTime = moment(new Date()).add(5 ,'s');
var intervalHolder = {};
console.log("go")
intervalHolder.interval = setInterval(() => {
if (moment(new Date()).isAfter(targetTime)) {
console.log('TimedOut');
clearInterval(intervalHolder.interval);
}
},1000);
<script src="https://momentjs.com/downloads/moment.js"></script>

jQuery/JavaScript - Repeating timer, save to MySQL upon reaching zero

I'm working on a small project, that combines Java(servlets) with some web elements. I've got a Java back-end that deals with registration and login. When the user has logged in, he/she arrives at the dashboard where a timer awaits them.
The timer should be set at 25 minutes and when the user presses 'start', it should start counting down to zero. When zero has been reached, I want the timer to save the timestamps (begin/end) to MySQL and automatically start a 5 minute timer.
I've been looking on Google for quite some time. jQuery seems the easiest option, but I'm genuinely struggling getting this started.
Is there anyone who could help me?
Perhaps guide me on the right path or (if you have time) have a little coding session?
On waiting page use Javascript:
var timeleft = 1500; // seconds left
var timer = setInterval(function () {
timeleft--;
// optional: update HTML element here
if (timeleft == 0) { saveTimestamp(); clearInterval(timer); }
}, 1000); // run every second
Then make saveTimestamp function either redirect browser to another page or make ajax call to sync with server.
On server, make a check if user reached this point after less than 25 minutes, and if he didn't (no cheating), perform standard writing to SQL (I can't help you much with server-side, as I've never worked with Java servlets).

Clear Form Fields on Inactivity

I'm currently working on a simple form that stores users inputted information to a database.
The form will be displayed on iPads at a Kiosk.
If a user walks up to the form and starts to fill in the fields, but doesn't finish and walks away, I want the form fields to clear for the next person.
This is being done to prevent someone from walking up to an iPad with half of the previous users information that was never submitted.
I know I'll have to use Javascript, but I have no clue where to start.
I would say handle the keydown event of the window object and save the current time. Something like this:
var timerID = null;
var timeoutDuration = 60000; // Put the timeout duration here
window.addEventListener('keydown', function(e) {
if(timerID !== null) {
clearTimeout(timerID);
timerID = null;
}
timerID = setTimeout(function() {
// Clear all the fields here
}, timeoutDuration);
}, false);
Here's a demo.
Why not just reload the page after a period of inactivity? Safer bet. Just use setTimeout and clearTimeout JavaScript functions to achieve this when the fields get updated to reset the timers. Use setTimeout to reload the page. This will ensure that the page is reset.
See Reload and JavaScript timing.
In my opinion, the best thing to use it the javaScript timing event.
This can be done by setTimeout() and clearTimeout() functions. Then in those functions you can address the input boxes document.getElementById("nameofElement") and then clear them.
Good example that is easy to follow see :
JavaScript Timing Events
Hope this helps.

How can I make my javascript chat polling script be more efficient?

For some reason this check for new chat messages causes a larger amount of browser (and to some extent server) load than I would expect. Anyone see any ways that I can make it more efficient, to lessen the load?
// Begin the cycle of refreshing the mini chat after the standard delay.
function startRefreshingMinichat(){
var secs = 30; // Chat checking frequency.
setTimeout(function (){
checkForNewChats();
startRefreshingMinichat(); // Loop the check for refresh.
}, secs*1000);
}
// Check for the latest chat and update if it's different.
function checkForNewChats(){
// Check whether the latest chat doesn't match the latest displayed chat.
// NOTE THAT THIS CALLBACK DOES NOT TRIGGER IMMEDIATELY.
$.getJSON('api.php?type=latest_chat_id&jsoncallback=?', function(data){
var newChats = false;
// Update global data stores if an update is needed.
if(updateDataStore(data.latest_chat_id, 'chat_id', 'latestChatId', 'chat_id')){
newChats = true;
}
if(newChats){ // there are new chats to show.
refreshMinichat(null, 50); // loads new chat content.
}
// Since this callback isn't immediate, any feedback has to occur whenever the callback finishes.
}); // End of getJSON function call.
}
Check out CometD. It's a js long-polling system I've used with some success for simple chat systems integrated with jQuery. (Last time I looked, there were a few jQuery specific implemetations, but I never found one that was robust enough for me.)
you can checkout this push engine so that you have not to poll for new data anymore.
check it out, its really cool.

Categories