javascript autologout for inactivity for 10 minutes - javascript

hello all i am writing a code for auto logout for inactivity for about 20 minutes which should interact with keyboard as well as mouse and i have following code which works for most of the function but it is not resetting the timer for mouse movement and keyboard activity.
var timoutWarning = 9000; // Display warning in 14 Mins.
var timoutNow = 9000; // Warning has been shown, give the user 1 minute to interact
var logoutUrl = 'logout.php'; // URL to logout page.
var warningTimer;
var timeoutTimer;
// Start warning timer.
function StartWarningTimer() {
warningTimer = setTimeout("IdleWarning()", timoutWarning);
}
// Reset timers.
function ResetTimeOutTimer() {
clearTimeout(timeoutTimer);
StartWarningTimer();
$("#timeout").hide();
}
// Show idle timeout warning dialog.
function IdleWarning() {
clearTimeout(warningTimer);
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
$("#timeout").show();
}
// Logout the user.
function IdleTimeout() {
window.location = logoutUrl;
}
$( document ).ready(function() {
StartWarningTimer();
});
$('html').mousemove(function() {
ResetTimeOutTimer();
});
i want the code should intract with mouse movement and keyboard press
all kind of help is appreciated please suggest me something

At first, you should not use setTimeout this way - inactive tabs getting slower, so there's no guarantee that your code will be executed in 14 minute. The better way to do that is to check repeatedly the elapsed time.
var startTime = +new Date();
function checkForWarning () {
if (+new Date() - startTime > maxInactiveTime) {
// show warning
}
}
You can track activity this way:
$(document)
.on('click', ResetTimeOutTimer)
.on('mousemove', ResetTimeOutTimer);
Hope it helps.

Related

Inactivity on the page, how to make a window? [duplicate]

Hello,
can't find a code :x Can someone post, or explain how can i make a Popup after 10minutes of inactive ?
When member is inactive of 10minutes after Page is loaded, the members will get a Popup with some Buttons and Text
<div>
<p>Away from keyboard?</p>
<ul class="button">
<li>I'm Back!</li>
</ul>
</div>
var seconds = 0;
var timeoutCounter = setInterval(function(){
seconds++;
if(sec == 600) {
// do stuff to launch popup
clearInterval(timeoutCounter);
}
}, 1000);
$(document).mousemove(function (e) {
clearInterval(timeoutCounter);
seconds = 0;
setInterval(timeoutCounter);
});
$(document).keypress(function (e) {
clearInterval(timeoutCounter);
seconds = 0;
setInterval(timeoutCounter);
});
This basically runs every second - and if it's the 600th second, it quits after running your code.
Source for idle checking
Attach the events to the document object along with the setTimeout method to display the popup. One way to do it is
var popupTimer,
TIME_OUT = 600;
// function that displays the popup
function displayPopup() {
// display the popup here
}
// Set the timeout to display the popup
popupTimer = setTimeout(displayPopup, TIME_OUT);
// attch events to the document object
// you can add more events here based on
// what events you want to track
$(document).on('click change keypress', function() {
// clear the timeout whenever the event is handled
clearTimeout(popupTimer);
// Reset the timer
popupTimer = setTimeout(displayPopup, TIME_OUT);
});

Chrome timer extension - how to keep timer running even when extension is closed?

I'm working on my first extension - Tea timer. After choosing a tea type/entering number of minutes timer will start running. The problem is that when I change my tab or close the extension, the timer will stop running although I would like it to run in the background. I'm not sure how to handle this with chrome.storage.
Here is my timer.js:
function timer(seconds) {
clearInterval(countdown);
const now = Date.now();
const then = now + seconds * 1000;
displayTimeLeft(seconds);
displayEndTime(then);
countdown = setInterval(() => {
const secondsLeft = Math.round((then - Date.now()) / 1000);
if (secondsLeft < 0) {
clearInterval(countdown);
const soundEffect = new Audio("tibetan.mp3");
soundEffect.play();
setTimeout(function() {
alert("Your tea is ready!");
}, 500);
return;
}
displayTimeLeft(secondsLeft);
}, 1000);
}
function displayTimeLeft(seconds) {
const minutes = Math.floor(seconds / 60);
const remainderSeconds = seconds % 60;
const display = `${minutes}:${
remainderSeconds < 10 ? "0" : ""
}${remainderSeconds}`;
if (timerDisplay) {
timerDisplay.textContent = display;
}
//console.log({ minutes, remainderSeconds });
}
function startTimer() {
const seconds = parseInt(this.dataset.time);
console.log(seconds);
timer(seconds);
}
buttons.forEach(button => button.addEventListener("click", startTimer));
background.js
chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([
{
conditions: [new chrome.declarativeContent.PageStateMatcher({})],
actions: [new chrome.declarativeContent.ShowAction()]
}
]);
});
});
Thank you all in advance!
Since time.js is part of a pop-up window, the code in that file (as well as the interval you've set using setInterval) will stop running as soon as the pop-up window is closed.
In order to make this work, you'll have to move the interval to the background page, the background page's context can be set to stay on as long as the browser is opened.
By the way, the code that is currently in background.js doesn't do anything and you only need something like that if you want to use page actions
Here is my approach for doing that:
background.js
let timerID;
let timerTime;
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.cmd === 'START_TIMER') {
timerTime = new Date(request.when);
timerID = setTimeout(() => {
// the time is app, alert the user.
}, timerTime.getTime() - Date.now());
} else if (request.cmd === 'GET_TIME') {
sendResponse({ time: timerTime });
}
});
timer.js
// Call this when the pop-up is shown
chrome.runtime.sendMessage({ cmd: 'GET_TIME' }, response => {
if (response.time) {
const time = new Date(response.time);
startTimer(time)
}
});
functions startTimer(time) {
if (time.getTime() > Date.now()) {
setInterval(() => {
// display the remaining time
}, 1000)
}
}
function startTime(time) {
chrome.runtime.sendMessage({ cmd: 'START_TIMER', when: time });
startTimer(time);
}
Essentially, when the user starts a timer, you send a message to the background script with a future date for when the timer is done. Then, in the background script you set a timeout to be triggered at that date so you can do something (play a sound) even if the pop-up window is closed.
Then, when the pop-up window is reopened, you send a message to the background script and it will send back the date for the timer that was previously set.
This can be improved, for now, this will work correctly as long as the browser is opened for the entire length of the timer, to make it work even if the browser is closed and reopened, you can save and restore the timer's date from storage.
Move the setInterval() code to background script and change "Persistent" property for background script in manifest to "True"
This allows extension to continue running background script even if the popup window of extension is closed and setInterval() will continue to run.
NOTE: You should be careful when you change "Persistent" property to "True". Make sure chrome webstore allows it without any issues.

Need to clear session and logout user after 30 sec or after close browser

code is in MVC and also every request are using ajax call so no change in url.
using below code i ll able to perform firt opration that logout user if user inactive of 30 sec. but not able to perform action when user logout.
<script>
$(function () {
$("body").on('click keypress', function () {
ResetThisSession();
});
});
var timeInSecondsAfterSessionOut = 30; // to change the session time out, change this value. Must be in seconds.
var secondTick = 0;
function ResetThisSession() {
secondTick = 0;
}
function StartThisSessionTimer() {
secondTick++;
console.log(secondTick);
if (secondTick > timeInSecondsAfterSessionOut) {
clearTimeout(tick);
window.location = '/Account/LogOff/0';
}
tick = setTimeout("StartThisSessionTimer()", 1000);
}
StartThisSessionTimer();
</script>
alse i tried the unload or beforeunload method of script but result not proper as expect.
need to logout user if user not perform any action on 30 sec or if user close browser.
thanks in advance.
as i see the var tick is local, and is defined in every tick, so the timeout is called every second:
function StartThisSessionTimer() {
secondTick++;
console.log(secondTick);
if (secondTick > timeInSecondsAfterSessionOut) {
clearTimeout(tick);
window.location = '/Account/LogOff/0';
}
tick = setTimeout("StartThisSessionTimer()", 1000);
}
Try to separate the initializiaton of the timeout, outside of the same scope of repeater of timeout.
tell us if is useful.
Tks

Show Popup after 10min of inactive

Hello,
can't find a code :x Can someone post, or explain how can i make a Popup after 10minutes of inactive ?
When member is inactive of 10minutes after Page is loaded, the members will get a Popup with some Buttons and Text
<div>
<p>Away from keyboard?</p>
<ul class="button">
<li>I'm Back!</li>
</ul>
</div>
var seconds = 0;
var timeoutCounter = setInterval(function(){
seconds++;
if(sec == 600) {
// do stuff to launch popup
clearInterval(timeoutCounter);
}
}, 1000);
$(document).mousemove(function (e) {
clearInterval(timeoutCounter);
seconds = 0;
setInterval(timeoutCounter);
});
$(document).keypress(function (e) {
clearInterval(timeoutCounter);
seconds = 0;
setInterval(timeoutCounter);
});
This basically runs every second - and if it's the 600th second, it quits after running your code.
Source for idle checking
Attach the events to the document object along with the setTimeout method to display the popup. One way to do it is
var popupTimer,
TIME_OUT = 600;
// function that displays the popup
function displayPopup() {
// display the popup here
}
// Set the timeout to display the popup
popupTimer = setTimeout(displayPopup, TIME_OUT);
// attch events to the document object
// you can add more events here based on
// what events you want to track
$(document).on('click change keypress', function() {
// clear the timeout whenever the event is handled
clearTimeout(popupTimer);
// Reset the timer
popupTimer = setTimeout(displayPopup, TIME_OUT);
});

how to keep the session active even i opened in multiple tabs in same browser

i would like to implement one thing.i opened my site in multiple tabs. while i work in one tab others tabs should not be timedout. it should be alive. how to keep alive for other tabs. i used below js to find idle time logout.
<script type="text/javascript">
idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval("timerIncrement()", 60000); // 1 minute
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
})
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 2) { // 30 minutes
var beforeTime = new Date()
var bminutes = beforeTime.getMinutes();
var bseconds = beforeTime.getSeconds();
var user='<?php echo Auth::getSessionUserFullName();?>';
if(user!='')
{
var timehours=beforeTime.getHours();
var timeoutmin=bminutes+1;
var timeoutseconds=bseconds-1;
if(timeoutseconds>59)
{
timeoutseconds=0;
timeoutmin=timeoutmin+1;
}
if(timeoutmin>59)
{
timeoutmin=0;
timehours=hours+1;
}
if(timehours>24)
{
timehours=0;
}
var ok=confirm("Your session expire time started at "+beforeTime.getHours()+":"+beforeTime.getMinutes()+":"+beforeTime.getSeconds()+".Please click 'OK' before "+timehours+":"+timeoutmin+":"+timeoutseconds+" to stay signed in.");
if(ok)
{
var currentTime = new Date()
var aminutes = currentTime.getMinutes();
var aseconds = currentTime.getSeconds();
var time=aminutes-bminutes;
if(aminutes>bminutes && aseconds>bseconds)
{
alert('Time out!!Please login again to access.');
window.location.href='<? echo APPLICATION_WEBROOT?>auth/logout';
return false;
}
else if(time>=2)
{
alert('Time out!!Please login again to access.');
window.location.href='<? echo APPLICATION_WEBROOT?>auth/logout';
return false;
}
else
{
return true;
}
}
else
{
window.location.href='<? echo APPLICATION_WEBROOT?>auth/logout';
}
}
}
}
</script>
Please help me. how to keep the sessions for all opened tabs.thanks in advance
The session is not tab specific. It is for the whole browser instance.
The session is extended when a user makes a request to the server. So depending on your application, you may have to generate regular requests to the server to extend that session.
For that, you can use the setInterval javascript function to trigger an AJAX call to your PHP backend.
Hope that helps...
BTW: be careful because some browsers do deactivate the tabs which don't have the user focus (Chrome for example) - it will not modify session... but some JS could be suspended.
One of the way I can think of is handle the session yourself in the server.
Here's a system that might work (welcome suggestions of improvement):
1) store your own custom session in server DB, with IP being the unique identifier.
2) whenever user interacts with your server, grab its IP and update the corresponding session stored in server. If that session has already timeout, redirect user to timeout page.
there might be many things that I haven't though through, but in my mind this should be a viable way to maintain session across tabs

Categories