I am using javascript setInterval() to check user idle time and show a popup alert before automatic logout. But it does not work for multiple tabs (working fine for single tab)
Following is my code :
localStorage.removeItem("idleTimeValue");
var idleInterval = setInterval(timerIncrement, 1000);
function timerIncrement()
{
if(localStorage.getItem("idleTimeValue")) {
idleTime = parseInt(localStorage.getItem("idleTimeValue")) + 1; //increments idle time by one second
} else {
idleTime = 1;
}
localStorage.setItem("idleTimeValue", idleTime);
var timeDiff = 600;
var totTimeRemaining = timeDiff-idleTime;
if(totTimeRemaining > 0) {
$('#timeoutWindow').modal('show');
var minutes = Math.floor(totTimeRemaining / 60);
var seconds = totTimeRemaining - minutes * 60;
$('#timeoutRemainingTime').html(minutes+" minutes and "+seconds+" seconds");
} else {
window.location = httpHost+"/account/index/logout";
}
}
$(this).click(function (e)
{
localStorage.removeItem("idleTimeValue");
$('#timeoutWindow').modal('hide');
});
I am setting the idle time in localStorage like -
localStorage.setItem("idleTimeValue", idleTime);
So if I open 3 tabs, setInterval() function will run in all tabs, also idleTime increments by 3 seconds instead of 1 second and time calculations is happening wrongly.
I need to show popup in all tabs and clicking continue in one tab should reflct in all other tabs.
Can anybody suggest a solution for this? Please help guys
Thank you guys, I got the solution for this.
I used a localStorage value with current time stored in it. If there is no value exists in localStorage["currentTime"], stored current time in localStorage .
var currentTime = new Date();
if ( !(localStorage.getItem("currentTime")) || (localStorage.getItem("currentTime") == "") )
{
idleTime = 0;
setTimeout(function() { localStorage.setItem("currentTime", currentTime)},5000); // current time is set to localStorage after seconds (it is for setting in multiple tabs)
}
All calculations to show timeout popup is done using localStorage.getItem("currentTime") value.
Then I set localStorage["currentTime"] to null if user is not idle (when user clicks somewhere)
$(this).click(function (e)
{
$('#timeoutWindow').modal('hide');
localStorage.setItem("currentTime", "");
idleTime = 0;
});
You can tweak your existing implementation like below to fullfill your requirement.
Step 1: Setup environment - Creating unique timer Id to isolate it from other timers
var timerId = 'timer-'+(new Date().getTime());
localStorage.setItem(timerId, '0');
modifyAllIdleTime('0');//i.e resetting all timers
var idleInterval = setInterval(timerIncrement, 1000);
function timerIncrement(){
// increament & Set only localStorage.getItem(timerId) so that it will not affect others
// Add logic to showHide
}
Step 2: Modifying Idle Time - call whenever other timer instance idle time need to be modified
function modifyAllIdleTime(idleTime) {
for(var i = 0; i < localStorage.length; i++) {
if(localStorage.key(i).indexOf('timer-') !== -1) { //if timer instance
localStorage.setItem(localStorage.key(i), idleTime);
}
}
}
Step 3: Exit - exit all timer whenever remaining time comes to 0 for any of the timer
modifyAllIdleTime('600');// where 600 is the max allowed idle time in sec
deleteTimer();//call this to cleanup localStorage before navigating user to logout screen
i want php session to be expired if there is no activity on the page for more than 10 to 20 minutes. Or user is not available for more than 20 min.Say we are taking an example of login, user logged in and after 20 min if there is no activity , it should expire the session and redirect to login page again.
Use Jquery
html or php page :
<body id="homepage" onload="set_interval()" onmousemove="reset_interval()" onclick="reset_interval()" onkeypress="reset_interval()" onscroll="reset_interval()">
jquery
//user login sessions
var timer = 0;
function set_interval() {
// the interval 'timer' is set as soon as the page loads
timer = setInterval("auto_logout()", 300000);
// the figure '10000' above indicates how many milliseconds the timer be set to.
// Eg: to set it to 5 mins, calculate 5min = 5x60 = 300 sec = 300,000 millisec.
// So set it to 300000
}
function reset_interval() {
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scroliing
//first step: clear the existing timer
if (timer != 0) {
clearInterval(timer);
timer = 0;
// second step: implement the timer again
timer = setInterval("auto_logout()", 300000);
// completed the reset of the timer
}
}
function auto_logout() {
// this function will redirect the user to the logout script
**window.location = "index.php?opt=Logout";**
}
LOGOUT page
if(#$_REQUEST['opt']=='Logout')
{
unset($_SESSION['uid']);
unset($_SESSION['username']);
}
Store the last request made time in session
<?php
$_SESSION['timeout'] = time();
?>
In every request happening, check how long ago they made their previous request (10 minutes in this example)
<?php
if ($_SESSION['timeout'] + 10 * 60 < time()) {
// destroy session & logout
} else {
$_SESSION['timeout'] = time();
}
?>
The Client-side solution:
Your page:
<script type="text/JavaScript">
var idleRefresh;
idleRefresh = setTimeout("location.href = 'unset.php';",30000);
windows.onmousemove = function() {
clearTimeOut(idleRefresh);
idleRefresh = setTimeout("location.href = 'unset.php';",30000);
};
</script>
unset.php: (Unset all session variables / specific login variables, and redirect user to login page)
<?php
session_unset();
header('Location: login.php');
?>
I would have added this add a comment to Arun's jquery solution, but don't have 50 reputation yet. I had to make some modifications to his code to get it working, for example, this:
timer = setInterval("auto_logout()", 300000);
Needs to be changed to this:
timer = setInterval( function(){ auto_logout() }, 300000);
I have included the fully revised code below:
HTML:
<body onload="setTimer()" onmousemove="resetTimer()" onclick="resetTimer()" onkeypress="resetTimer()" onscroll="resetTimer()">
And Javascript is:
// Variables: timer, timeout
var t, to = 10000;
// Setup the timer
function setTimer() {
t = setInterval( function(){
logout()
}, to);
}
// Reset the timer
function resetTimer() {
if (t > 0) {
clearInterval(t);
setTimer();
}
}
// Logs user out
function logout() {
window.location = "login.php";
}
As Arun has mentioned, change timeout (to) to whatever you need. In the above example I have it set to 10000, which is only 10 seconds.
Hope this helps - and thanks again for Arun for posting the original code.
// JQUERY SCRIPT;
var reset = 60000;
var timer = reset;
$('body').on('click keyup mousemove', function(){
timer=reset;
});
// COUNTDOWN FUNCTION 'ct' SHOW THE TIMING ON YOUR SIGNOUT BUTTON AND
// WILL REDIRECT TO LOGOUT ACTION AFTER THE REACH SET TIMEOUT;
function ct(){
$('#so').text(timer/1000+' Sec. SIGN OUT');
timer=timer-1000;
if(timer==0){
window.location = 'logout.php';
}
}
// EXECUTE 'ct' FUNCTION AFTER EVERY 1 SEC.
setInterval('ct()', 1000);
/* CSS CODE OF SIGNOUT BUTTON */
#so{
background-color: tomato;
padding:8px 20px;
color:#fff;
border-radius: 4px;
text-decoration: none;
}
h3, #so{font-family: Segoe UI;}
<!-- LIBRARY -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- HTML CODE -->
SIGN OUT
<h3>RESET TIMER WITH - MOVE CURSOR, KEY UP & CLICK<h3>
Below is the function use to check for the session of my page. The page will reload after I clicked the alert message.
var timeleft = 60;
function checkTime() {
timeLeft--;
if (timeLeft == 30 )
{
alert("30 secs left.");
window.location.reload();
}
}
Is there anyway that the timeleft continue minus (if the user din't not notice the alert message) so that it will redirect to logout page when the timeleft is = 0.
alert() is a modal, it stops javascript execution. Check this code:
var start = new Date();
var start2;
window.setTimeout(function() {
var end = new Date();
var result = "time from start: " + (end.getTime() - start.getTime())
result += "\ntime from alert: " + (end.getTime() - start2.getTime())
result += "\nalert was open for: " + (start2.getTime() - start.getTime())
alert(result);
}, 500);
window.setTimeout(function() {
alert("hello");
start2 = new Date();
}, 100);
Fiddle for upper code: http://jsfiddle.net/aorcsik/vfeH2/1/
Check out this code, it shows that even setTimeout is stopped during alert(), but you can check how much time the user was looking at the alert, and update your counter (timeLeft) by decreasing with the measured time devided by your ticker delay.
Solution: So my solution would be to measure how much time the user looks at the alert modal, and whenever he clicks ok, check if his session ended, if yes redirect to logout, else do the usual redirect.
var start = new Date();
alert("xxx");
var t = (new Date()).getDate() - start.getDate();
if (t / 1000 > timeLeft) {
/* logout */
} else {
/* redirect */
}
Note: another solution would be to use some html popup instead of the javascript alert, which would not block javascript execution
If you want an async alert you can try this
setTimeout(function() { alert('30 secs left'); }, 1);
But if you want a timed logout you can do something like this instead:
function checkTime() {
setInterval(function(){alert("30 secs left.")},30000); // shown at 30 seconds
setInterval(function(){logout()},60000); // called at 60 seconds
}
function logout() {
// logout functionality
}
your code comment is strange
first you are using a number (60) and you consider it as (two minutes) then alert it is(30 seconds left)..
Anyways ..
you want to count down and when there is only 30 seconds left you want to reload the page!!
the problem here is that when you reload the page you will reset the count down from (60 as in your code)
the solution is one of the following:
1- save the countdown in localstorage as pointed out by #Fabrizio and when the page is reloaded again then use the saved counterdown value.
however this solution assume that your user browser can save to localstorage
2- second solution is that you post your page with the countdown and reload it with the count down..
let us say that you page address is: www.myexampleaddress.com/mypage
then you call the address as follow :www.myexampleaddress.com/mypage?timeleft=30
and catch this on the server and reload the page from the server with value in your querystring ..
so your coude after the alert should be like this
var myURL = location.href+'?timeleft=30';
location.href =myURL;
i hope that help :)
Ok coming straight to the point
I have a text box and few other things on a page
if the user is typing in the textbox the page should not refresh otherwise it should refresh after a certain interval
I searched alot and cannot find anything similar
I am new to javascript
Here is a simple example of this. A check runs every 3 seconds. if nothing has been typed in it will refresh, if something has been typed in it will wait 3 seconds before refreshing.
http://jsfiddle.net/9ARrG/
HTML
<input onkeyup="resetTimer = true">
JS
resetTimer = false;
setInterval(function() {
if(!resetTimer) {
location.reload();
}
resetTimer = false;
}, 3000);
Give your input/textarea an id
<input id="textbox" />
// OR
<textarea id="textbox"></textarea>
Then, setup a timer to refresh the page. If there's a change, reset the timer.
var originalTimer = 15000; // here's the original time until page refreshes
var timer = originalTimer; // timer to track whether to refresh page
// now every 1 second, update the timer
setInterval(function() {
timer -= 1000; // timer has gone down 1 sec
// if timer is less than 0, refresh page
if (timer <= 0) window.location.reload();
},1000); // repeat every 1 second (1000 ms)
document.getElementById("textbox").onchange = function() {
// detect textbox changes, reset timer
timer = originalTimer;
}
Use the document.activeElement property to conditionally determine what element has focus.
function refreshPageUnlessFocusedOn (el) {
setInterval(function () {
if(el !== document.activeElement) {
document.location.reload();
}
}, 3000)
}
refreshPageUnlessFocusedOn(document.querySelector('textarea'));
Check out the jsfiddle here for a working sample.
How can I automatically reload a webpage, if there have been no activity on the page for a given period of time?
This can be accomplished without javascript, with this metatag:
<meta http-equiv="refresh" content="5" >
where content ="5" are the seconds that the page will wait until refreshed.
But you said only if there was no activity, what kind for activity would that be?
If you want to refresh the page if there is no activity then you need to figure out how to define activity. Let's say we refresh the page every minute unless someone presses a key or moves the mouse. This uses jQuery for event binding:
<script>
var time = new Date().getTime();
$(document.body).bind("mousemove keypress", function(e) {
time = new Date().getTime();
});
function refresh() {
if(new Date().getTime() - time >= 60000)
window.location.reload(true);
else
setTimeout(refresh, 10000);
}
setTimeout(refresh, 10000);
</script>
I have built a complete javascript solution as well that does not require jquery. Might be able to turn it into a plugin. I use it for fluid auto-refreshing, but it looks like it could help you here.
JSFiddle AutoRefresh
// Refresh Rate is how often you want to refresh the page
// bassed off the user inactivity.
var refresh_rate = 200; //<-- In seconds, change to your needs
var last_user_action = 0;
var has_focus = false;
var lost_focus_count = 0;
// If the user loses focus on the browser to many times
// we want to refresh anyway even if they are typing.
// This is so we don't get the browser locked into
// a state where the refresh never happens.
var focus_margin = 10;
// Reset the Timer on users last action
function reset() {
last_user_action = 0;
console.log("Reset");
}
function windowHasFocus() {
has_focus = true;
}
function windowLostFocus() {
has_focus = false;
lost_focus_count++;
console.log(lost_focus_count + " <~ Lost Focus");
}
// Count Down that executes ever second
setInterval(function () {
last_user_action++;
refreshCheck();
}, 1000);
// The code that checks if the window needs to reload
function refreshCheck() {
var focus = window.onfocus;
if ((last_user_action >= refresh_rate && !has_focus && document.readyState == "complete") || lost_focus_count > focus_margin) {
window.location.reload(); // If this is called no reset is needed
reset(); // We want to reset just to make sure the location reload is not called.
}
}
window.addEventListener("focus", windowHasFocus, false);
window.addEventListener("blur", windowLostFocus, false);
window.addEventListener("click", reset, false);
window.addEventListener("mousemove", reset, false);
window.addEventListener("keypress", reset, false);
window.addEventListener("scroll", reset, false);
document.addEventListener("touchMove", reset, false);
document.addEventListener("touchEnd", reset, false);
<script type="text/javascript">
var timeout = setTimeout("location.reload(true);",600000);
function resetTimeout() {
clearTimeout(timeout);
timeout = setTimeout("location.reload(true);",600000);
}
</script>
Above will refresh the page every 10 minutes unless resetTimeout() is called. For example:
clicky
Based on the accepted answer of arturnt. This is a slightly optimized version, but does essentially the same thing:
var time = new Date().getTime();
$(document.body).bind("mousemove keypress", function () {
time = new Date().getTime();
});
setInterval(function() {
if (new Date().getTime() - time >= 60000) {
window.location.reload(true);
}
}, 1000);
Only difference is that this version uses setInterval instead of setTimeout, which makes the code more compact.
var bd = document.getElementsByTagName('body')[0];
var time = new Date().getTime();
bd.onmousemove = goLoad;
function goLoad() {
if(new Date().getTime() - time >= 1200000) {
time = new Date().getTime();
window.location.reload(true);
}else{
time = new Date().getTime();
}
}
Each time you move the mouse it will check the last time you moved the mouse. If the time interval is greater than 20' it will reload the page, else it will renew the last-time-you-moved-the-mouse.
use JavaScript setInterval method:
setInterval(function(){ location.reload(); }, 3000);
Auto reload with target of your choice. In this case target is _self set to itself,but you could change the reload page by simply changing the window.open('self.location', '_self'); code to something like this examplewindow.top.location="window.open('http://www.YourPageAdress.com', '_self'";.
With a confirmation ALERT message:
<script language="JavaScript">
function set_interval() {
//the interval 'timer' is set as soon as the page loads
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
itimer=setInterval("auto_logout()",timeoutMins);
atimer=setInterval("alert_idle()",timeout1Mins);
}
function reset_interval() {
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scrolling
//first step: clear the existing timer
clearInterval(itimer);
clearInterval(atimer);
//second step: implement the timer again
itimer=setInterval("auto_logout()",timeoutMins);
atimer=setInterval("alert_idle()",timeout1Mins);
}
function alert_idle() {
var answer = confirm("Session About To Timeout\n\n You will be automatically logged out.\n Confirm to remain logged in.")
if (answer){
reset_interval();
}
else{
auto_logout();
}
}
function auto_logout() {
//this function will redirect the user to the logout script
window.open('self.location', '_self');
}
</script>
Without confirmation alert:
<script language="JavaScript">
function set_interval() {
//the interval 'timer' is set as soon as the page loads
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
itimer=setInterval("auto_logout()",timeoutMins);
}
function reset_interval() {
var timeoutMins = 1000 * 1 * 15; // 15 seconds
var timeout1Mins = 1000 * 1 * 13; // 13 seconds
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scrolling
//first step: clear the existing timer
clearInterval(itimer);
clearInterval(atimer);
//second step: implement the timer again
itimer=setInterval("auto_logout()",timeoutMins);
}
function auto_logout() {
//this function will redirect the user to the logout script
window.open('self.location', '_self');
}
</script>
Body code is the SAME for both solutions:
<body onLoad="set_interval(); document.form1.exp_dat.focus();" onKeyPress="reset_interval();" onmousemove="reset_interval();" onclick="reset_interval();" onscroll="reset_interval();">
I came up with a slightly different solution, because I found that setInterval isn't really accurate, see: setInterval timing slowly drifts away from staying accurate
// Based on https://stackoverflow.com/a/15279599
// Refresh Rate is how often you want to refresh the page
// based off the user inactivity (in seconds).
var refresh_after = 20;
var last_user_action = new Date();
// Reset the Timer on users last action
function reset() {
last_user_action = new Date();
}
// Countdown that executes every second.
setInterval(function () {
refreshCheck();
}, 1000);
// The code that checks if the window needs to reload
function refreshCheck() {
var expire_time = new Date(last_user_action);
expire_time.setSeconds(expire_time.getSeconds() + refresh_after);
now = new Date();
if (now.getTime() >= expire_time.getTime() && document.readyState == "complete") {
window.location.href = window.location.href; // We do this to discard the POST data.
}
}
window.addEventListener("click", reset, false);
window.addEventListener("mousemove", reset, false);
window.addEventListener("keypress", reset, false);
window.addEventListener("scroll", reset, false);
document.addEventListener("touchMove", reset, false);
document.addEventListener("touchEnd", reset, false);
Yes dear,then you have to use Ajax technology. to changes contents of
particular html tag:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Ajax Page</title>
<script>
setInterval(function () { autoloadpage(); }, 30000); // it will call the function autoload() after each 30 seconds.
function autoloadpage() {
$.ajax({
url: "URL of the destination page",
type: "POST",
success: function(data) {
$("div#wrapper").html(data); // here the wrapper is main div
}
});
}
</script>
</head>
<body>
<div id="wrapper">
contents will be changed automatically.
</div>
</body>
</html>
I would consider activity to be whether or not the user is focused on the window. For example, when you click from one window to another (e.g. Google Chrome to iTunes, or Tab 1 to Tab 2 within an internet browser), the webpage can send a callback saying "Im out of focus!" or "Im in focus!". One could use jQuery to harness this possible lack of activity to do whatever they wanted. If I were in your position, I would use the following code to check for focus every 5 seconds, etc and reload if no focus.
var window_focus;
$(window).focus(function() {
window_focus = true;
}).blur(function() {
window_focus = false;
});
function checkReload(){
if(!window_focus){
location.reload(); // if not focused, reload
}
}
setInterval(checkReload, 5000); // check if not focused, every 5 seconds
And finally the most simple solution:
With alert confirmation:
<script type="text/javascript">
// Set timeout variables.
var timoutWarning = 3000; // Display warning in 1Mins.
var timoutNow = 4000; // Timeout in 2 mins.
var warningTimer;
var timeoutTimer;
// Start timers.
function StartTimers() {
warningTimer = setTimeout("IdleWarning()", timoutWarning);
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
}
// Reset timers.
function ResetTimers() {
clearTimeout(warningTimer);
clearTimeout(timeoutTimer);
StartTimers();
$("#timeout").dialog('close');
}
// Show idle timeout warning dialog.
function IdleWarning() {
var answer = confirm("Session About To Timeout\n\n You will be automatically logged out.\n Confirm to remain logged in.")
if (answer){
ResetTimers();
}
else{
IdleTimeout();
}
}
// Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
function IdleTimeout() {
window.open(self.location,'_top');
}
</script>
Without alert confirmation:
<script type="text/javascript">
// Set timeout variables.
var timoutWarning = 3000; // Display warning in 1Mins.
var timoutNow = 4000; // Timeout in 2 mins.
var warningTimer;
var timeoutTimer;
// Start timers.
function StartTimers() {
warningTimer = setTimeout(timoutWarning);
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
}
// Reset timers.
function ResetTimers() {
clearTimeout(warningTimer);
clearTimeout(timeoutTimer);
StartTimers();
$("#timeout").dialog('close');
}
// Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
function IdleTimeout() {
window.open(self.location,'_top');
}
</script>
Body code is the SAME for both solutions
<body onload="StartTimers();" onmousemove="ResetTimers();" onKeyPress="ResetTimers();">
With on page confirmation text instead of alert
Since this is another method to auto load if inactive I give it a second answer. This one is more simple and easier to understand.
With reload confirmation on the page
<script language="javaScript" type="text/javascript">
<!--
var autoCloseTimer;
var timeoutObject;
var timePeriod = 5100; // 5,1 seconds
var warnPeriod = 5000; // 5 seconds
// Warning period should always be a bit shorter then time period
function promptForClose() {
autoCloseDiv.style.display = 'block';
autoCloseTimer = setTimeout("definitelyClose()", warnPeriod);
}
function autoClose() {
autoCloseDiv.style.display = 'block'; //shows message on page
autoCloseTimer = setTimeout("definitelyClose()", timePeriod); //starts countdown to closure
}
function cancelClose() {
clearTimeout(autoCloseTimer); //stops auto-close timer
autoCloseDiv.style.display = 'none'; //hides message
}
function resetTimeout() {
clearTimeout(timeoutObject); //stops timer
timeoutObject = setTimeout("promptForClose()", timePeriod); //restarts timer from 0
}
function definitelyClose() {
// If you use want targeted reload: parent.Iframe0.location.href = "https://URLHERE.com/"
// or this: window.open('http://www.YourPageAdress.com', '_self');
// of for the same page reload use: window.top.location=self.location;
// or window.open(self.location;, '_self');
window.top.location=self.location;
}
-->
</script>
Confirmation box when using with on page confirmation
<div class="leftcolNon">
<div id='autoCloseDiv' style="display:none">
<center>
<b>Inactivity warning!</b><br />
This page will Reloads automatically unless you hit 'Cancel.'</p>
<input type='button' value='Load' onclick='definitelyClose();' />
<input type='button' value='Cancel' onclick='cancelClose();' />
</center>
</div>
</div>
Body codes for both are the SAME
<body onmousedown="resetTimeout();" onmouseup="resetTimeout();" onmousemove="resetTimeout();" onkeydown="resetTimeout();" onload="timeoutObject=setTimeout('promptForClose()',timePeriod);">
NOTE: If you do not want to have the on page confirmation, use Without confirmation
<script language="javaScript" type="text/javascript">
<!--
var autoCloseTimer;
var timeoutObject;
var timePeriod = 5000; // 5 seconds
function resetTimeout() {
clearTimeout(timeoutObject); //stops timer
timeoutObject = setTimeout("definitelyClose()", timePeriod); //restarts timer from 0
}
function definitelyClose() {
// If you use want targeted reload: parent.Iframe0.location.href = "https://URLHERE.com/"
// or this: window.open('http://www.YourPageAdress.com', '_self');
// of for the same page reload use: window.top.location=self.location;
// or window.open(self.location;, '_self');
window.top.location=self.location;
}
-->
</script>
Using LocalStorage to keep track of the last time of activity, we can write the reload function as follows
function reloadPage(expiryDurationMins) {
const lastInteraction = window.localStorage.getItem('lastinteraction')
if (!lastInteraction) return // no interaction recorded since page load
const inactiveDurationMins = (Date.now() - Number(lastInteraction)) / 60000
const pageExpired = inactiveDurationMins >= expiryDurationMins
if (pageExpired) window.location.reload()
}
Then we create an arrow function which saves the last time of interaction in milliseconds(String)
const saveLastInteraction = () => window.localStorage.setItem('last', Date.now().toString())
We will need to listen to the beforeunload event in the browser to clear our lastinteraction record so we don't get stuck in an infinite reload loop.
window.addEventListener('beforeunload', () => window.localStorage.removeItem('lastinteraction'))
The user activity events we will need to monitor would be mousemove and keypress. We store the last interaction time when the user moves the mouse or presses a key on the keyboard
window.addEventListener('mousemove', saveLastInteraction)
window.addEventListener('keypress', saveLastInteraction)
To set up our final listener, we will use the load event.
On page load, we use the setInterval function to check if the page has expired after a certain period.
const expiryDurationMins = 1
window.addEventListener('load', setInterval.bind(null, reloadPage.bind(null, expiryDurationMins), 1000))
I am doing it like this:
let lastActionTaken = new Date().getTime();
function checkLastAction() {
let now = new Date().getTime();
if (now - lastActionTaken > 1000 * 60 * 60) window.location.reload();
else lastActionTaken = now;
}
window.addEventListener("mousemove", checkLastAction);
window.addEventListener("touchstart", checkLastAction);
window.addEventListener("keydown", checkLastAction);
This will reload the page as soon as the user moves their mouse, hits a key or touches a touchscreen if it has been inactive for 1 hour. Also, this takes care of the focus as well, so if a user is moving their mouse in a different program and then come back to this window it will reload, which is good because the point is to not have old data being shown.
Many of these other answers either don't answer the main part of the question "with no activity", or they are incredibly, unnecessarily complex. I have taken the accepted answer (here: https://stackoverflow.com/a/4644315/9008140 )
and modified it to take advantage of the fact you can assign timers to variables. This allows us to get rid of the second timer, as well as the timestamp.
/**
* create a timer that refreshes the page after the number of
minutes has passed without user interaction.
* Moving the mouse or pressing a key on the current page will start
the timer over.
* #param {any} minutes
*/
var refreshTimer;
function setPageRefreshTimer(minutes) {
var refreshInterval = minutes * 60 * 1000; //interval is in milliseconds. We refresh every x minutes.
$(document.body).bind("mousemove keypress", function (e) {
if (refreshTimer != null && refreshTimer != undefined) {
window.clearTimeout(refreshTimer);
}
refreshTimer = window.setTimeout(function () { window.location.reload(true); }, refreshInterval);
});
refreshTimer = window.setTimeout(function () { window.location.reload(true); }, refreshInterval);
}
This sample code will refresh based on a passed in parameter in minutes, with an accuracy as great as a javascript timer can be. In testing, always less than a second. I created this as a function but you can pull it into your page if you wish.
This task is very easy use following code in html header section
<head> <meta http-equiv="refresh" content="30" /> </head>
It will refresh your page after 30 seconds.