Code Monkey home page Code Monkey logo

jtimeout's Introduction

jTimeout

by HTMLGuy, LLC (https://htmlguy.com)

example jtimeout

Demo

https://htmlguyllc.github.io/jTimeout/

What is it?

jQuery session timeout handler - Tracks a user's session expiration and lets them know before their session times out so they can extend it. Then tells them when it has expired so they can login again. The only time the timer isn't reset but could/should be, is when an AJAX call is made to a page that doesn't include jTimeout. You'll have to just call "$.jTimeout.reset(1440);" each time an AJAX call is made to reset the timer. Passing the number of seconds is optional, it'll default to the $.jTimeout.defaults.timeoutAfter param. If you don't implement this reset, no big deal. The session doesn't actually have to be expired for this plugin to work. It'll manually call the logout page on timeout.

Dependencies

Available on NPM

https://www.npmjs.com/package/jtimeout

npm install jtimeout

How to use

<html>
<head>
<link rel="stylesheet" src="jAlert-master/dist/jAlert.css"/>
</head>
<body>
<!-- your site content -->
<script src='https://code.jquery.com/jquery-1.11.3.min.js'></script> <!-- Include jQuery -->
<script src='jAlert-master/dist/jAlert.min.js'></script> <!-- Include jAlert - Get it here: https://github.com/HTMLGuyLLC/jAlert -->
<script src='jTimeout-master/dist/jTimeout.min.js'></script> <!-- Include this Plugin -->
<script>
  $(function(){
    $.jTimeout( options ); //options outlined below.
  });
</script>
</body>
</html>

Options

$(function(){
   $.jTimeout({
		expiration_key: 'jtimeout-session-expiration', //key used to store expiration in localstorage (change this for multiple timers)

		flashTitle: true, //whether or not to flash the tab/title bar when about to timeout, or after timing out
		flashTitleSpeed: 500, //how quickly to switch between the original title, and the warning text
		flashingTitleText: '**WARNING**', //what to show in the tab/title bar when about to timeout, or after timing out
		originalTitle: document.title, //store the original title of this page

		timeoutAfter: 1440, //pass this from server side to be fully-dynamic. For PHP: ini_get('session.gc_maxlifetime'); - 1440 is generally the default timeout
		heartbeat: 1, //how many seconds in between checking the expiration - warning: changing this can effect your prior countdown warning and timeout - for best results, stick with 1

		extendOnMouseMove: true, //Whether or not to extend the session when the mouse is moved
		mouseDebounce: 30, //How many seconds between extending the session when the mouse is moved (instead of extending a billion times within 5 seconds)
		onMouseMove: false, //Override the standard $.get() request that uses the extendUrl with your own function.

		extendUrl: '/dashboard', //URL to request in order to extend the session.
		logoutUrl: '/logout', //URL to request in order to force a logout after the timeout. This way you can end a session early based on a shorter timeout OR if the front-end timeout doesn't sync with the backend one perfectly, you don't look like an idiot.
		loginUrl: '/login', //URL to send a customer when they want to log back in

		secondsPrior: 60, //how many seconds before timing out to run the next callback (onPriorCallback)
		onPriorCallback: false, //override the popup that shows when getting within x seconds of timing out

		onClickExtend: false, //override the click to extend button callback

		onTimeout: false, //override the timeout function if you'd like
		onSessionExtended: false //override the session extension method (triggered only after a timeout)
	}
   );
   $.jTimeout().getExpiration(); //gets the expiration date string
   $.jTimeout().getSecondsTillExpiration(); //gets the number of seconds until the session expires
});

###Seting the default session length in PHP (recommended)

$.jTimeout({ 'timeoutAfter': <?php echo ini_get('session.gc_maxlifetime'); ?> });

How to reset the expiration

$.jTimeout().reset();

How to set the timer to a specific number of seconds

$.jTimeout().setExpiration(1440);

Recommended reset usage

Everytime you request a page that extends a user's session, use the reset function:

$(document).ajaxStop(function(){
  $.jTimeout().reset();
});
//warning: If $.ajax() or $.ajaxSetup() is called with the global option set to false, the .ajaxStop() method will not fire.

If you want to use your own modal

jTimeout already works out of the box with jAlert, but can fairly easily configured to work with your own custom callbacks. Just override the callbacks like this:

$.jTimeout({
  onTimeout: function(jTimeout){
      console.log('Session timed out!');
  },
  onPriorCallback: function(jTimeout){
      var secondsLeft = jTimeout.getSecondsTillExpiration();
      console.log('You will be timed out in: '+secondsLeft+' seconds');
  },
  onSessionExtended:function(jTimeout){
      console.log('Session timed out, but then was extended by another tab or request.');
  }
});

jtimeout's People

Contributors

designosis avatar ggirard avatar htmlguyllc avatar i24737 avatar kukoman avatar locutus83 avatar mozami avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

jtimeout's Issues

Version + NPM questions

Hey,
This is the very best timeout implementation I've seen, thank you!
I do have two suggestions:

  1. On the code page it says version is 3, however the src and dist content all says 2.1
  2. Register jTimeout on NPM, so I can easily see whenever you submit a new release :)

Thanks again.

onClickExtend

I'm using chrome(87.0.4280.88) but have tried firefox and edge

onClickExtend doesnt seem to do anything.

I am trying to allow onclick and onmousemove to reset timeout
the only way i was able to get the time out to reset onclick was to attach it to the $(document).on('click', function()
here is my testing code::

<title>jQuery Session Timeout Script</title>
<link rel='stylesheet' type='text/css' href='https://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css'>
<link rel="stylesheet" type="text/css" href="CSS/jAlert/dist/jAlert.css">

<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
  <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->

<script src='https://code.jquery.com/jquery-3.3.1.min.js'></script>
<script src='https://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js'></script>
<script src='https://htmlguyllc.github.io/jAlert/dist/jAlert.min.js'></script> <!--Needed -->
<script src='JS/jTimeout.js'></script>
<script> $(function(){ $(Document).on('click', function(){ $.jTimeout.reset(80); }); $.jTimeout({ timeoutAfter: 80, loginUrl: 'index.php', logoutUrl: 'index.php', extendOnMouseMove: true, });
                var timer,
  				setTimer = function(){
  					timer = window.setInterval(function(){
  						$('#secondsRemaining').val( $.jTimeout().getSecondsTillExpiration() );
  					}, 1000);
  				};

  				setTimer();

  			});

  		</script>

  </div>
	
</div>

any help would be appreciated

Removing the modal on another tab after extending session

Hi,

Thanks for the great works. I am gonna integrate your lib to may application, using custom modal not jAlert. Everything looks good except when I have multiple tab and click on "exntend session" button:

Current tab:

  • title flashing is stopped
  • modal is closed

Another tab:

  • title flashing is stopped
  • modal is NOT closed.

Do you have any idea how to close the modal on another tab? I was looking for closing it on onClickExtend event, but it seems like it never been called.

Thanks

I actually have a question

Does this still log the user out if they are using a mobile device and they left the tab open or does it wait until the user clicks on that tab again to log the user out?

Pop up didn't close on another tabs after logout.

time

1.) Open the demo link on two different tabs
2.) Then I Clicked on the button 60 seconds left after clicking poup comes up with decrementing seconds.
3.) After me session timeout on both tabs, I clicked on one popup to login Again
4.) Then on first tab the poup didn't close and it is showing the value (1440 seconds)

Transform time in mm:ss

Hello everyone,

How can i transform the time in seconds in time for example 1440 seconds show on input curTime 23m 30s

a bit of clunky behaviour

Hi Shane,

excellent library I must say. Would you consider one more additional function/property?
Although I understand that resetting the timeout count by mouse is kind of cool but it's really confusing for a new user. When my session times out, I come back and naturally I want to click the alert button. What happens however is it goes away and "I don't know" what happened, I didn't even had the time to read it because it disappeared immediately after I moved my mouse :(
as quick workaround I changed the if statement in the mousemove event:

if (!jTimeout.mouseMoved && ($('#jTimeoutAlert').length == 0 && $('#jTimedoutAlert').length == 0)) {

Now it triggers only when one of the windows are not rendered.
Would you consider adding one more property or changing the behaviour?

thank you for you excellent work

It really starts when I click inside the website

This only appears when I click the website

onPriorCallback: function(jTimeout){ //tell them they will be timing out soon! //to get the current time: var secondsLeft = jTimeout.getTimer(); console.log('You will be timed out in: '+secondsLeft+' seconds'); }

seems like to be not working on ready

$2(function(){ $2.jTimeout({

jAlerts are not closed in other tabs

Not sure if it's my implementation that is wrong but when I click extend my session in one tab the jAlert stays open in the other tabs but the countdown is resetter correctly.

I changed this bit of code in my implementation

hideCountdownAlert: function()
            {
                timeout.timeoutWarning = false;

                var timeoutAlert = $('.jAlert');

                if (timeoutAlert.length > 0)
                {
                    timeoutAlert.closeAlert();
                }
            },

Don't know if it's a correct fix or my implementation is wrong, let me know.

Default event callbacks set to false from documentation throw an error

Hello, this is my config :

<link rel="stylesheet" src="/assets/jalert/jAlert.css"/>
<script src="/assets/jalert/jAlert.min.js"></script> 
<script src="/assets/jalert/jAlert-functions.min.js"></script> 
 <script src="/assets/jalert/jTimeout.min.js"></script> 
      <script>
          $(function () {
            $.jTimeout({
              flashTitle: true, //whether or not to flash the tab/title bar when about to timeout, or after timing out
              flashTitleSpeed: 500, //how quickly to switch between the original title, and the warning text
              flashingTitleText: '**WARNING**', //what to show in the tab/title bar when about to timeout, or after timing out
              originalTitle: document.title, //store the original title of this page

              timeoutAfter: 60, //pass this from server side to be fully-dynamic. For PHP: ini_get('session.gc_maxlifetime'); - 1440 is generally the default timeout
              heartbeat: 1, //how many seconds in between checking the expiration - warning: changing this can effect your prior countdown warning and timeout - for best results, stick with 1

              extendOnMouseMove: true, //Whether or not to extend the session when the mouse is moved
              mouseDebounce: 30, //How many seconds between extending the session when the mouse is moved (instead of extending a billion times within 5 seconds)
              onMouseMove: false, //Override the standard $.get() request that uses the extendUrl with your own function.

              extendUrl: '/index.xhtml', //URL to request in order to extend the session.
              logoutUrl: '/auto-logout.xhtml', //URL to request in order to force a logout after the timeout. This way you can end a session early based on a shorter timeout OR if the front-end timeout doesn't sync with the backend one perfectly, you don't look like an idiot.
              loginUrl: '/login.xhtml', //URL to send a customer when they want to log back in

              secondsPrior: 30, //how many seconds before timing out to run the next callback (onPriorCallback)
              onPriorCallback: false, //override the popup that shows when getting within x seconds of timing out

              onClickExtend: false, //override the click to extend button callback

              onTimeout: false, //override the timeout function if you'd like
              onSessionExtended: false //override the session extension method (triggered only after a timeout)
            }
            );
            $.jTimeout().getExpiration(); //gets the expiration date string
            $.jTimeout().getSecondsTillExpiration(); //gets the number of seconds until the session expires
          });
      </script>

jQuery 3.4.1 / Chrome v 75.0

i get this error :

jTimeout.min.js:10 Uncaught TypeError: c.options.onPriorCallback is not a function
at countdown (jTimeout.min.js:10)
and then a series of :
jTimeout.min.js:10 Uncaught TypeError: c.options.onMouseMove is not a function
at HTMLBodyElement. (jTimeout.min.js:10)
at HTMLBodyElement.dispatch (jquery.js.xhtml?ln=primefaces&v=7.0.5:2)
at HTMLBodyElement.v.handle (jquery.js.xhtml?ln=primefaces&v=7.0.5:2)

the flashingTitleText: 'WARNING' is showed on the page title

Custom callbacks don't fire onSessionExtended

When using custom callbacks, onSessionExtended event is not being fired:

$.jTimeout(
    {
        expiration_key: 'jtimeout-session-expiration',
        flashingTitleText: '!!!',
        timeoutAfter: 25,
        extendUrl: '/ping',
        logoutUrl: '/logout',
        loginUrl: '/login',
        secondsPrior: 10
        onPriorCallback: function () {
            $('#modal-session-timeout').modal('show'); //works fine
        },
        onTimeout: function () {
            window.location = '/logout'; // works fine
        },
        onSessionExtended: function () {
            $('#modal-session-timeout').modal('hide'); // does not get fired
        }
    }
);

$('.btn-extend-session').on('click', function () {
    $.jTimeout.reset();
    $('#modal-session-timeout').modal('hide');
});

Session gets renewed but boostrap modal window remains open. Any idea how to fix that?

extendOnMouseMove: true does not work.

I have added "extendOnMouseMove: true," to the script on my page as well as in the jTimeout.js script but a mouse movement on the page does nothing either before or after the alert appears.

Browser: Chrome Version 97.0.4692.71

Reset after onTimeout alert is shown

Hi,

Thanks for the nice plugins.
I am displaying the loginurl in an iframe, once the user logs in I call the reset() function to restart the loop which shows the default onPriorCallback alert but keeps counting below zero and never displays the onTimeout again

How can I restart the countdown loop again after onTimeout has been shown?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.