examples.session.timeout.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. (function( $ ) {
  2. 'use strict';
  3. var SessionTimeout = {
  4. options: {
  5. keepAliveUrl: '',
  6. alertOn: 15000, // ms
  7. timeoutOn: 20000 // ms
  8. },
  9. alertTimer: null,
  10. timeoutTimer: null,
  11. initialize: function() {
  12. this
  13. .start()
  14. .setup();
  15. },
  16. start: function() {
  17. var _self = this;
  18. this.alertTimer = setTimeout(function() {
  19. _self.onAlert();
  20. }, this.options.alertOn );
  21. this.timeoutTimer = setTimeout(function() {
  22. _self.onTimeout();
  23. }, this.options.timeoutOn );
  24. return this;
  25. },
  26. // bind success callback for all ajax requests
  27. setup: function() {
  28. var _self = this;
  29. // if server returns successfuly,
  30. // then the session is renewed.
  31. // thats why we reset here the counter
  32. $( document ).ajaxSuccess(function() {
  33. _self.reset();
  34. });
  35. return this;
  36. },
  37. reset: function() {
  38. clearTimeout(this.alertTimer);
  39. clearTimeout(this.timeoutTimer);
  40. this.start();
  41. return this;
  42. },
  43. keepAlive: function() {
  44. // we don't have session on demo,
  45. // so the code above prevent a request to be made
  46. // in your project, please remove the next 3 lines of code
  47. if ( !this.options.keepAliveUrl ) {
  48. this.reset();
  49. return;
  50. }
  51. var _self = this;
  52. $.post( this.options.keepAliveUrl, function( data ) {
  53. _self.reset();
  54. });
  55. },
  56. // ------------------------------------------------------------------------
  57. // CUSTOMIZE HERE
  58. // ------------------------------------------------------------------------
  59. onAlert: function() {
  60. // if you want to show some warning
  61. // TODO: remove this confirm (it breaks the logic and it's ugly)
  62. var renew = confirm( 'Your session is about to expire, do you want to renew?' );
  63. if ( renew ) {
  64. this.keepAlive();
  65. }
  66. // if you want session to not expire
  67. // this.keepAlive();
  68. },
  69. onTimeout: function() {
  70. self.location.href = 'pages-signin.html';
  71. }
  72. };
  73. $(function() {
  74. SessionTimeout.initialize();
  75. });
  76. }).apply(this, [ jQuery ]);