thorst / jquery-idletimer Goto Github PK
View Code? Open in Web Editor NEWThis project forked from nzakas/yui-misc
provides you a way to monitor user activity with a page.
License: MIT License
This project forked from nzakas/yui-misc
provides you a way to monitor user activity with a page.
License: MIT License
I don't believe your fiddle is working in IE 11 -- http://jsfiddle.net/thorst/2aGL4/
It loads as 'active' and never changes.
I'm using IE Browser Version 11.850.15063.0
In my implementation with IE 11 and jquery 3.3.1 on Windows 10, the mouse wheel does not work and users can't input into textareas or use dropdown select when idleTimer is instantiated on $(document)
I saw that the syncTimerId feature is not available through Bower or Grunt, and it's because no tag for 1.1.0 has been released. Any plans of doing that soon, since that feature seems useful for mobile devices?
We are using this plugin in our project.
Currently we ran into issue that large part of users are coming from mobile devices.
Hence feature-request: Add support for touch events.
Please document a function with which I can manually fire 'idle.idleTimer' for the purpose of writing my tests
Looks like Chrome with strict MIME type checking enabled will not execute the jsfiddle external JS (http://jsfiddle.net/thorst/2aGL4/4/):
One workaround is to change the external JS from the raw.github link to http://thorst.github.io/jquery-idletimer/prod/src/idle-timer.js
Would be great if there is any way to call a method with a separated time interval to call to an specific service to mantain the backend session alive
Like:
$( document ).idleTimer( {
keepAlive:{
timeout: 5000, //every 5 seconds call a determined backend function
script: 'http://localhost/wakeup.php'
}
});
I keep getting:
Uncaught TypeError: ((jQuery.event.special[handleObj.origType] || {}).handle || handleObj.handler).apply is not a function....
for each of the events I use in "events" option.
However, if I change the idleTimer code (line 300) from:
jqElem.on($.trim((opts.events + " ").split(" ").join("._idleTimer ")), function (e) {
handleEvent(e);
}, supportsPassive ? { passive: true } : false);
to:
jqElem.on($.trim((opts.events + " ").split(" ").join("._idleTimer ")), function (e) {
handleEvent(e);
});
It's not happening any more. Seems that the check for support of passive events in combination with jQuery namespaced events doesn't work.
Even if i move and click the mouse in the iframe, it still remains idle. Is there a way around this?
Iframe does not work with document
either.
Thanks
I've been implementing your plugin today and I think I've run across an issue that is either a bug or an inherent browser problem, but I can't figure out which.
I used one of your examples as my reference implementation, stripping out the keepalive bits because my server side session management has its own timeout mechanism. Your cross-tab/window feature works perfectly for avoiding the popup, but when I dismiss it in one tab, it stays open in the other(s), and they eventually trigger the logout event.
This is my full code, which like I said is mostly the same as your example:
<script>
(function ($) {
var
session = {
//Logout Settings
inactiveTimeout: 10000, //(ms) The time until we display a warning message
warningTimeout: 30000, //(ms) The time until we log them out
minWarning: 5000, //(ms) If they come back to page (on mobile), The minumum amount, before we just log them out
warningStart: null, //Date time the warning was started
warningTimer: null, //Timer running every second to countdown to logout
logout: function () { //Logout function once warningTimeout has expired
window.location = '/index.cfm?action=login.logout';
}
};
$(document).on("idle.idleTimer", function (event, elem, obj) {
//Get time when user was last active
var
diff = (+new Date()) - obj.lastActive - obj.timeout,
warning = (+new Date()) - diff
;
//On mobile js is paused, so see if this was triggered while we were sleeping
if (diff >= session.warningTimeout || warning <= session.minWarning) {
window.location = '/index.cfm?action=login.logout';
} else {
//Show dialog, and note the time
$('#sessionSecondsRemaining').html(Math.round((session.warningTimeout - diff) / 1000));
$("#sessionTimoutModal").modal("show");
session.warningStart = (+new Date()) - diff;
//Update counter downer every second
session.warningTimer = setInterval(function () {
var remaining = Math.round((session.warningTimeout / 1000) - (((+new Date()) - session.warningStart) / 1000));
if (remaining >= 0) {
$('#sessionSecondsRemaining').html(remaining);
} else {
session.logout();
}
}, 1000)
}
});
//User clicked ok to extend session
$("#extendSession").click(function () {
clearTimeout(session.warningTimer);
});
//User clicked logout
$("#logoutSession").click(function () {
session.logout();
});
//Set up the timer, if inactive for 10 seconds log them out
$(document).idleTimer({
timeout:session.inactiveTimeout,
timerSyncId:"compendium-logout-timer"
});
})(jQuery);
</script>
Hi there,
I feel this might be my mistake, but if I download the latest version (from dist/, either the minified or unminified version) and include it on my website, with chrome 24.0.1312.56 m I get (also fails on IE)
Uncaught TypeError: undefined is not a function
Which is weird because I definitively included Jquery before including the file for timer. The error is on this line:
( function( $ ) { # Uncaught TypeError: undefined is not a function
This diff solves it on my case:
4,5d3
< ( function( $ ) {
<
143,144d140
<
< })( jQuery );
$ is jQuery in my application, I guess it would break in some other cases. Frankly, I don't see anything wrong with the code (and I don't know what's causing it!), but this certainly fixes it.
Please reveiw the code below:
/*! Idle Timer v1.1.0 2016-03-21 | https://github.com/thorst/jquery-idletimer | (c) 2016 Paul Irish | Licensed MIT */
!function(a){a.idleTimer=function(b,c){var d;"object"==typeof b?(d=b,b=null):"number"==typeof b&&(d={timeout:b},b=null),c=c||document,d=a.extend({idle:!1,timeout:3e4,events:"mousemove keydown wheel DOMMouseScroll mousewheel mousedown touchstart touchmove MSPointerDown MSPointerMove"},d);var e=a(c),f=e.data("idleTimerObj")||{},g=function(b){var d=a.data(c,"idleTimerObj")||{};d.idle=!d.idle,d.olddate=+new Date;var e=a.Event((d.idle?"idle":"active")+".idleTimer");a(c).trigger(e,[c,a.extend({},d),b])},h=function(b){var d=a.data(c,"idleTimerObj")||{};if(("storage"!==b.type||b.originalEvent.key===d.timerSyncId)&&null==d.remaining){if("mousemove"===b.type){if(b.pageX===d.pageX&&b.pageY===d.pageY)return;if("undefined"==typeof b.pageX&&"undefined"==typeof b.pageY)return;var e=+new Date-d.olddate;if(200>e)return}clearTimeout(d.tId),d.idle&&g(b),d.lastActive=+new Date,d.pageX=b.pageX,d.pageY=b.pageY,"storage"!==b.type&&d.timerSyncId&&"undefined"!=typeof localStorage&&localStorage.setItem(d.timerSyncId,d.lastActive),d.tId=setTimeout(g,d.timeout)}},i=function(){var b=a.data(c,"idleTimerObj")||{};b.idle=b.idleBackup,b.olddate=+new Date,b.lastActive=b.olddate,b.remaining=null,clearTimeout(b.tId),b.idle||(b.tId=setTimeout(g,b.timeout))},j=function(){var b=a.data(c,"idleTimerObj")||{};null==b.remaining&&(b.remaining=b.timeout-(+new Date-b.olddate),clearTimeout(b.tId))},k=function(){var b=a.data(c,"idleTimerObj")||{};null!=b.remaining&&(b.idle||(b.tId=setTimeout(g,b.remaining)),b.remaining=null)},l=function(){var b=a.data(c,"idleTimerObj")||{};clearTimeout(b.tId),e.removeData("idleTimerObj"),e.off("._idleTimer")},m=function(){var b=a.data(c,"idleTimerObj")||{};if(b.idle)return 0;if(null!=b.remaining)return b.remaining;var d=b.timeout-(+new Date-b.lastActive);return 0>d&&(d=0),d};if(null===b&&"undefined"!=typeof f.idle)return i(),e;if(null===b);else{if(null!==b&&"undefined"==typeof f.idle)return!1;if("destroy"===b)return l(),e;if("pause"===b)return j(),e;if("resume"===b)return k(),e;if("reset"===b)return i(),e;if("getRemainingTime"===b)return m();if("getElapsedTime"===b)return+new Date-f.olddate;if("getLastActiveTime"===b)return f.lastActive;if("isIdle"===b)return f.idle}return e.on(a.trim((d.events+" ").split(" ").join("._idleTimer ")),function(a){h(a)}),d.timerSyncId&&a(window).bind("storage",h),f=a.extend({},{olddate:+new Date,lastActive:+new Date,idle:d.idle,idleBackup:d.idle,timeout:d.timeout,remaining:null,timerSyncId:d.timerSyncId,tId:null,pageX:null,pageY:null}),f.idle||(f.tId=setTimeout(g,f.timeout)),a.data(c,"idleTimerObj",f),e},a.fn.idleTimer=function(b){return this[0]?a.idleTimer(b,this[0]):this}}(jQuery);
var _firstRun = true;
$(document).ready(function() {
if(_firstRun){
var isLogin = $('#isLogined').val();
var maxIdleTime = 1800000; // 30 mins
var minTimeSession = $("#minSessionTime").val();
var convertMinPopup = 1800000 - minTimeSession;
var minutes = Math.floor(convertMinPopup / 60000);
var seconds = ((convertMinPopup % 60000) / 1000).toFixed(0);
var timerPopUp = minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
document.getElementById('timer').innerHTML = timerPopUp;
function countDown(){
console.log("CountDown function called!!!");
var presentTime = document.getElementById('timer').innerHTML;
var timeArray = presentTime.split(/[:]+/);
var m = timeArray[0];
var s = checkSecond((timeArray[1] - 1));
if(s==59){m=m-1}
if(m == 0 && s == 0){
$("#timeoutContainer").hide();
logout();
}
document.getElementById('timer').innerHTML = m + ":" + s;
}
function timer(){
console.log("calling timer Function!!!");
setInterval(countDown,1000)
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec}
if (sec < 0) {sec = "59"}
return sec;
}
$( document ).idleTimer(minTimeSession);
$( document ).on( "idle.idleTimer", function(){
if(isLogin == "true"){
$("#timeoutContainer").show();
console.log('before function called!!!');
timer();
}
});
function logout(){
$.ajax({
type: "POST",
url: ACC.config.contextPath + "/logout",
success: function (response) {
window.location = ACC.config.contextPath + "/logout";
}
});
}
function checkSecond(sec) {
if (sec < 10 && sec >= 0) {sec = "0" + sec}
if (sec < 0) {sec = "59"}
return sec;
}
$("#inactivity_ok").click(function(){
window.location = window.location;
});
$("#logoutButton").click(function(){
logout();
});
_firstRun = false;
}
});
Once the page load idle is not getting triggered, please help me to fix the issues.
Thanks
For some reason when I try to install this component using bower, I don't get a bower.json file, I get a .bower.json file and it has no main in it. What's the name of the component in bower? There seem to be multiple with the same name.
Idletimer does not seem to work properly when attached to an element. See the jsFiddle at http://jsfiddle.net/peterrr73/C3w7f/ : the idle event on a div element fires, then responds to an activate event -- and then appears to die. Please help!
I can get my function to start, and I can get it to stop, but I can't get it to restart again after stopping it.
function idlecheck(){
$(document).idleTimer( 5000 );
$(document).bind("idle.idleTimer", function(){
//functionality to occur when idle
$('#menu').fadeOut(1000);
});
$(document).bind("active.idleTimer", function(){
//functionality to occur when active again
$('#menu').fadeIn(1000);
});
}
// start the timer when the doc is ready.
$(document).ready(function(){
idlecheck();
});
I set up a button to disable the timer.
$('.disabletimer').click(function(x) {
$(document).idleTimer("destroy");
}
And then one to start it again.
$('.enabletimer').click(function(x) {
idlecheck();
}
Once the destroy item has been run, i can't start the idle timer at all.
Funny item is that if I don't have the idlecheck run on load, the "enabletimer" button will let make it start.
Is there a better way to pause or stop/restart the timer?
I've set the timeout value as 1 hour, that would be a parameter of 3600000. Will this be feasible.
works great in safari and chrome
First of all, everything is my fault. Sorry.
Second of all, I think we can improve the performance of this script. :)
We currently bind to all of these events to judge if a user is active:
events: "mousemove keydown wheel DOMMouseScroll mousewheel mousedown touchstart touchmove MSPointerDown MSPointerMove"
This makes sense in a way because we really want to know if the user does anything, sure. But…
The key issue here is that in many cases the browser cannot update the UI until the event handler has finished. So the user's scroll, mousemove, or touch is completely held up while it waits for our script to finish before actually getting closer to showing the user the outcome from that interaction.
This is described really well in this video:
https://www.youtube.com/watch?v=YyQYhhy1dZI#t=945 watch from 15:45 until 25:00At the end, you can see a shot of the "show scroll bottlenecks" feature in devtools where this script triggers a bunch:
Chrome's touch maestro Rick Byers also gave a long explanation of why touch handlers wreck performance: https://plus.google.com/+RickByers/posts/cmzrtyBYPQc?e=-RedirectToSandbox
The touch events are unnecessary because a touch will end up triggering mousedown
anyway.
https://patrickhlauke.github.io/touch/tests/results/ has all the details
the original list:
If we remove superfluous events that we can catch with another binding:
Binding to mousewheel, mousescroll is not great, as Nat & Tom offer in that video above. Resig offered similar advice in 2011 (see best practices). A better approach is polling for changes in scrollTop
.
it's got great support and is a very simple indicator of "idle", so we could turn off polling then.
So then we're left with..
mousemove keydown wheel DOMMouseScroll mousewheel mousedown touchstart touchmove MSPointerDown MSPointerMove (and a page-visibility-aware scrollTop polling loop)
I think that's a fine list: mousedown mousemove keydown
. We won't regress how well we monitor idle/active and we'll speed up all interactions with the pages considerably.
@thorst how does that sound to you?
The following line outputs an object, instead of the elapsed time in ms
console.log($(document).idleTimer("getElapsedTime"));
Should maybe add events for IE10 (MSPointerDown and MSPointerMove)?
http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx
I'm still experiencing the issue I described in #16 (comment). However now I have had time to investigate what I was experiencing.
Tested on 2/27/2014 with Chrome Version 33.0.1750.117 m && Firefox 27.0.1.
Im testing https://raw.github.com/mikesherov/jquery-idletimer/master/dist/idle-timer.js
The mouse move event is triggered (line 97). obj.idle (line 106) is false, so it never triggers the toggle until the timeout expires once.
I havent tracked it down, but it seems like the textareas timer is triggering for the document timer, and thats why #status shows as idle (step number 2 above)
This isn't an issue when the timeout is 5 seconds, because it will go in and out of idle state frequently.
But my timeout is high (13 minutes) so for it to perform this cycle, its too late and my server side's session has expired.
I thought just setting idle to true or startImmediately to false (or both) would be enough. But the result is the same, after the timeout the banner shows idle even though I'm moving my mouse.
Looking at #1 I believe a fix for that would solve my issue. However, i still need to support ie8, so the proposed fix (pagevisibility) wouldn't work.
I beleive there are 2 issues:
You can see it in action at http://jsfiddle.net/sujay/yJFq7/
Both the events are not being triggered. But the state in data('idleTimerObj')
works as expected.
Please let me know if I'm missing something here.
We had this issue reported: primefaces/primefaces#5084
And a PR submitted to fix the issue: primefaces/primefaces#5083
However the PrimeFaces project would prefer not to customize this component and was wondering if you could add this feature to your core library? You can review that PR there may be a better way to do it?
Thanks for your attention and support!
I noticed that package.json currently has a main
field as prescribed, however a new tag is not published.
Would help with using with jspm and like.
I'm currently updating a code base to use jQuery 3.4.1 with the assistance of the jQuery Migrate tool. It is flagging up a deprecation issue within idletimer.
Run the following JSFiddle with the dev tools open and you'll see the warning "JQMIGRATE: jQuery.fn.bind() is deprecated".
http://jsfiddle.net/3x2sqzb1/ (it wouldn't allow direct CDN to idletimer, so I had to paste it for demo purposes).
The instructions advise updating the call from "bind" to "on" - https://github.com/jquery/jquery-migrate/blob/master/warnings.md.
Is this something that can be updated and pushed out so we can continue using this library without risk of it becoming obsolete?
Thanks!
from dmtr:
The user is assumed to be 'active for the first x seconds', this is certainly true for the document, but not so for the document elements. I guess natural thing to do would be to check if a mouse is 'over' [the document or element] to determine the initial state. If it is - initial state would be 'active', if it is not - 'idle'. That seems to be pretty consistent.
We should probably add an initial callback event to differentiate the immediate idling from the eventual idling.
Event mousemove triggered always on plugin change state if using modal window (jquery for example, with overlay) for displaying some popup on idle state.
So if mouse is in document area (even if no mouse moving) so idle state finished without any activity.
I have a patch for this situation:
should remove event 'mousemove' in 'events' variable
after row
//assign appropriate event handlers
we put this code:
$(elem).mousemove(function (event) {
if (event.pageX != obj.mX || event.pageY != obj.mY) {
obj.mX = event.pageX;
obj.mY = event.pageY;
//handleUserEvent(elem); - not work for me, so I trigger another event
$(elem).trigger('keydown');
}
});
When I install rails-assets-jquery-idletimer via rails-assets.org, I get the following message,
This component doesn't define main assets in bower.json.
Please open new pull request in component's repository:
https://github.com/mikesherov/jquery-idletimer
In my application i have ajax setup to show loader and this is done globally. Issue is that when idle ping the server the loader is showing. My purpose is to set ajax global attribute to false or to be configurable.
When I start the timer and call getLastActiveTime function, getLastActiveTime returns false.
$( document ).idleTimer();
var time = $( document ).idleTimer("getLastActiveTime");
Tracing through the code, it looks like firstParam is undefined. So line 250 skipped over because undefined === null is false, and ends up returning false at line 255.
My current workaround is to call idleTimer(null). In which case, lastActiveTime correctly returns the last active time.
$( document ).idleTimer(null);
var time = $( document ).idleTimer("getLastActiveTime");
@paulirish is taking down his copy of the demo.
This looks like an awesome script.
I need something just like this but if the end user is watching a presentation video we don't want it redirecting. How difficult would it be to add a video listener to this?
Thanks!
Why not @mikesherov!?
For the autologout demo, on lines 147+
//On mobile js is paused, so see if this was triggered while we were sleeping
if (diff >= session.warningTimeout || warning <= session.minWarning) {
$("#mdlLoggedOut").modal("show");
} else {
To make sure I understand the code correctly:
Let's say warningTimeout is 10 minutes, and minWarning is 5 seconds.
This will logout the user if they are on a different app for 10 or more minutes, which make sense.
But wouldn't the warning <= session.minWarning
logout the user if they went to an app for less than 5 seconds? I think it's supposed to be warning >= session.minWarning
.
If am wrong about this, could you please tell me why? Thanks in advance.
Hello,
We are experiencing a new issue with the tilling sprites in PIXI V4.
Here is a fiddle that show the issue : https://jsfiddle.net/sa0zj0vq/1/
When the scale is set to 0.5 (line 6 of the fiddle), holes appear in the repeating pattern. If the scale is set to 1, the issue disappear. We looked into the code of the V4 and we didn't find any difference with our V3 version which works well in this case.
Is it out of scope to listen to and raise events when a users blurs the window.
Example would be:
$(window).focus(function() {
//do something
});
$(window).blur(function() {
//do something
});
I've implemented your timeout workflow based on the autologout demo, and I tried to set it for 30 min. Although it works on desktop, on mobile devices (tested on iPad and iPhone) if you go to the Home screen doesn't work. Any hints on how to make it work with Apple devices properly?
a fix for 1.7 support from @terminal-case
now means that idle-timer requires 1.7. would be nice to allow support before that too..
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.