Jquery timeout code not re-running after first time user extends session - javascript

I wrote a Jquery function that blacks out the screen after a certain amount of inactivity, creates a pop-up that allows the user to click a button to stay logged in, and logs them out (closing the application window) if they do not respond in time.
The environment is ASP.NET (VB). We don't technically use master pages, but we do have a parent page in which our header, footer and nav reside, and my Jquery code is called from that window, loaded via an IFrame.
I've got a function in the child window that reports activity (currently keydown, mousedown and blur) to the parent window, and resets the timer. My code seems to be working fine, except in one scenario. If the user is prompted with the timeout warning, and then they click the button to continue their session, if they take no action on the page (mouseclick, keydown, etc.) then the timeout code is not running a second time.
Here is my main jquery function:
function pop_init() {
// show modal div
$("html").css("overflow", "hidden");
$("body").append("<div id='popup_overlay'></div><div id='popup_window'></div>");
//$("#popup_overlay").click(popup_remove); // removed to make sure user clicks button to continue session.
$("#popup_overlay").addClass("popup_overlayBG");
$("#popup_overlay").fadeIn("slow");
// build warning box
$("#popup_window").append("<h1>Warning!!!</h1>");
$("#popup_window").append("<p id='popup_message'><center>Your session is about to expire. Please click the button below to continue working without losing your session.</center></p>");
$("#popup_window").append("<div class='buttons'><center><button id='continue' class='positive' type='submit'><img src='images/green-checkmark.png' alt=''/> Continue Working</button></center></div>");
// attach action to button
$("#continue").click(session_refresh);
// display warning window
popup_position(400, 300);
$("#popup_window").css({ display: "block" }); //for safari using css instead of show
$("#continue").focus();
$("#continue").blur();
// set pop-up timeout
SESSION_ALIVE = false;
window.setTimeout(popup_expired, WARNING_TIME);
}
Here is the code from the parent window:
<script language="javascript" type="text/javascript">
var timer = false;
window.reportChildActivity = function() {
if (timer !== false) {
clearTimeout(timer);
}
//SESSION_ALIVE = true;
timer = window.setTimeout(pop_init, SESSION_TIME);
}
</script>
Here is the code from the child window:
<script type="text/javascript">
$(document).ready(function() {
window.parent.reportChildActivity();
});
</script>
<script type="text/javascript">
$(document).bind("mousedown keydown blur", function() {
window.parent.reportChildActivity();
});
The last script runs in a file (VB.NET ascx file) that builds the header/menu options for every page in our system.
The last line in the pop_init function clearly should be re-starting the timer, but for some reason it doesn't seem to be working.
Thanks for any help and insight you may have.
Forgot to add my code for the session_refresh function:
function session_refresh() {
SESSION_ALIVE = true;
$(".buttons").hide();
$("#popup_message").html("<center><br />Thank you! You may now resume using the system.<br /></center>");
window.setTimeout(popup_remove, 1000);
$("#popup_window").fadeOut("slow", function() { $('#popup_window,#popup_overlay').trigger("unload").unbind().remove(); });
var timer = false;
window.reportChildActivity = function() {
if (timer !== false) {
clearTimeout(timer);
}
timer = window.setTimeout(pop_init, SESSION_TIME);
}
}

use this: http://www.erichynds.com/jquery/a-new-and-improved-jquery-idle-timeout-plugin/

You need to restart your timer after the user clicks the button.

Well, I seem to have fixed the problem by changing this:
var timer = false;
window.reportChildActivity = function() {
if (timer !== false) {
clearTimeout(timer);
}
timer = window.setTimeout(pop_init, SESSION_TIME);
}
to this:
if (timer !== false) {
clearTimeout(timer);
}
timer = window.setTimeout(pop_init, SESSION_TIME);
I didn't need to re-declare the reportChildActivity function as I was.

Related

toggle button to start/stop refreshing my page

I'm trying to make sort of a toggle button to start and stop a page from refreshing itself but for some reason the stopping process isn't working. is my logic correct?
this is my code:
<button id = "toggleButton" onclick = "initRefresh()" > Stop Refresh </button>
<script>
function reloadUrl() {
window.location.replace(
[location.protocol, '//', location.host, location.pathname].join('')
);
}
function initRefresh() {
if ($('#toggleButton').text() == 'Start Refresh') {
$('#toggleButton').text("Stop Refresh");
t = window.setTimeout(reloadUrl, 45000);
} else {
$('#toggleButton').text("Start Refresh");
clearTimeout(t);
}
};
var t = window.setTimeout(reloadUrl, 45000);
</script>
the default option (on first load) is on. so when the user goes into the page for the first time 45 seconds later the page will refresh.
Thanks for the help.
I believe the problem comes from the initialization of the t variable.
You start a setTimeout when the page loads.
Change it to var t = null and the above code should work.
Your code (as in question) is working 100%.
But it will not work if placed your code inside $(document).ready event.

How to use setInterval to have Refresh on by default but off with a switch

I would like to use setInterval to control a refresh of my page. I would like to have it running by default (on when the page loads) but I need to be able to turn it off at certain times. So I've written what you see below. The problem is that the refresh is not on when the page first displays. It only comes on after I click the button twice to re-activate the update the setInterval controls.
My html button definition looks like this;
<button id="autoref" type="button" name="autoref" onclick="stopAutoRef();">Stop Auto Ref</button>
My stopAutoRef function looks like this;
function stopAutoRef() {
if ($("#autoref").text() == "Stop Auto Ref") {
$("#autoref").html('Start Auto Ref'); // You see this if Refresh is not automatically happening
clearInterval();
}else {$("#autoref").html('Stop Auto Ref'); // You see this if Refresh is automatically happening
setInterval(function() {showActivities(document.getElementById("select1").value);}, 60000);
}
}
setInterval returns an ID which must be passed to clearInterval to stop it. You'd also want to call your function, startAutoRef(), immediately in addition to on click to initiate the default behavior of refreshing.
var autoRefId = null;
function stopAutoRef() {
if (autoRefId !== null) {
$("#autoref").html('Start Auto Ref'); // You see this if Refresh is not automatically happening
clearInterval(autoRefId);
autoRefId = null;
} else {
$("#autoref").html('Stop Auto Ref'); // You see this if Refresh is automatically happening
autoRefId = setInterval(function() {showActivities(document.getElementById("select1").value);}, 60000);
}
}
stopAutoRef();
clearinterval generally requires a argument of which function to stop. so try this maybe?
try this:
HTML:
<button id = 'b' onclick = 'stop(this)' value = 'true'>Stop ref</button>
Javascript:
var myfunc = setInterval(function(){
location.reload();
},1000);;
function stop(button){
if(button.innerHTML == 'Stop ref'){
button.innerHTML = 'Start ref';
clearInterval(myfunc);
}
else{
button.innerHTML = 'Stop ref';
myfunc = setInterval(function(){
location.reload();
},1000);;
}
}

setTimeout function if user not active

I can do something such as the following every 30 seconds to reload the page, and the backend logic will determine which session have been invalidated:
setInterval(function () {
location.reload()
}, 30000);
However, how would I only run this 30s location.reload() if the user is not active? For example, how banks will have a user-timeout if the user has not been active on the page (which only starts counting after the user is 'inactive'). How would this be done?
One way is to track mousemoves. If the user has taken focus away from the page, or lost interest, there will usually be no mouse activity:
(function() {
var lastMove = Date.now();
document.onmousemove = function() {
lastMove = Date.now();
}
setInterval(function() {
var diff = Date.now() - lastMove;
if (diff > 1000) {
console.log('Inactive for ' + diff + ' ms');
}
}, 1000);
}());
First define what "active" means. "Active" means probably, sending a mouse click and a keystroke.
Then, design your own handler for these situations, something like this:
// Reseting the reload timer
MyActivityWatchdog.prototype.resetReloadTimer = function(event) {
var reloadTimeInterval = 30000;
var timerId = null;
...
if (timerId) {
window.clearInterval(timerId);
}
timerId = window.setInterval( reload... , reloadTimeInterval);
...
};
Then, make sure the necessary event handler will call resetReloadTimer(). For that, you have to look what your software already does. Are there key press handlers? Are there mouse movement handlers? Without knowing your code, registering keypress or mousemove on document or window and could be a good start:
window.onmousemove = function() {
...
activityWatchdog.resetReloadTimer();
...
};
But like this, be prepared that child elements like buttons etc. won't fire the event, and that there are already different event handlers. The compromise will be finding a good set of elements with registered handlers that makes sure "active" will be recognized. E.g. if you have a big rich text editor in your application, it may be enough to register only there. So maybe you can just add the call to resetReloadTimer() to the code there.
To solve the problem, use window blur and focus, if the person is not there for 30 seconds ,it will go in the else condition otherwise it will reload the page .
setTimeout(function(){
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
$('div').text("user is not active on page ");
break;
case "focus":
location.reload()
break;
}
}
$(this).data("prevType", e.type);
})},30000);
DEMO : http://jsfiddle.net/rpawdg6w/2/
You can check user Session in a background , for example send AJAX call every 30 - 60 seconds. And if AJAX's response will be insufficient (e.g. Session expired) then you can reload the page.
var timer;
function checkSession() {
$.ajax({
url : 'checksession.php',
success: function(response) {
if (response == false) {
location.reload();
}
}
});
clearTimeout(timer);
timer = setTimeout(checkSession,30 * 1000);
}
checkSession();

How to create timer in my case?

I am trying to have my button doing two things.
init a timer to call a function
call the same function
I have something like the following
test.prototype.setupEvent= function(){
var instance = this;
$('#btn').on('click', function(){
clearInterval(instance.timer);
this.showStuff()
instance.timer=setInterval(function(){
instance.showStuff()
},10000);
})
}
test.prototype.showStuff= function(btnID){
//jump to another page
}
My problem is that I want the user be able to see some contents after 10 second when they first click it, however, if they click the button again before 10 second is up, they can see the contents too. I am not sure how to distinguish the two different states with one click event. Can anyone help me out? Thanks!
Try
test.prototype.setupEvent = function () {
var instance = this;
$('#btn').on('click', function () {
//if there is a timer running then clear the timer, show the content and delete the timer reference
if (instance.timer) {
clearInterval(instance.timer);
instance.showStuff();
delete instance.timer
return;
}
//also you may want to use setTimeout() not setInverval()
instance.timer = setInterval(function () {
instance.showStuff();
delete instance.timer
}, 10000);
})
}
test.prototype.showStuff = function (btnID) {
//jump to another page
}

Close popup after x minutes unless there was activity

I have a link that when clicked, opens a new window using:
var win = window.open(url,....);
This window contains a flash game.
I want to close the window after 20 minutes of inactivity.
I know I can create a timeout using:
var t = setTimeout("dosomething()", 5000)
But how can I figure out if there was activity or not on the popup?
If the user interacts with the flash, can I get this information still via the dom events?
I want to avoid the situation of closing the window while they are playing :)
This is in a IE based environment.
theInterval = 0;
function doSomething(){
do something;
}
function ScheduleDoSomething(){
theInterval = setInterval(function () {
doSomething();}, timeToClose);
}
jQuery(document).keydown(function (e) {
clearInterval(theInterval);scheduleDoSomething();
});
I hope this helps.
How about adding a listening event for the mousemove, keypress, and click events and clearing the timer every time the events happen.
var t = setTimeout(closeWindow, 5000);
$(document).on('mousemove keypress click', function(){
clearTimeout(t);
t = setTimeout(closeWindow, 5000);
});
function closeWindow(){
window.close();
}

Categories