javascript - 在使用 Javascript 设计注销后自动重定向?

标签 javascript ruby-on-rails devise

我正在使用 Devise,自动注销效果很好。

但是,在用户发出另一个请求之前,他们不会被告知他们已注销,此时他们将被重定向到登录页面。对于 AJAX 功能,这不是很好,它要么静默失败,要么引发异常。

Devise wiki 好像没有例子,请问有没有标准的解决方案?带有倒数计时器的 javascript 弹出窗口,如果用户没有单击“保持登录状态”,它会进行重定向?

最佳答案

我最终实现了类似于下面的 jscript 超时。

一些未回答的问题:

  • 切换到另一个标签页时会发生什么?
  • 在 IE 中工作?

application.js

//= require timer

// redirect user after 15 minutes of inactivity - should match Devise.timeout_in + 1 second grace period
$(function() {
    var logout_timer = new Timer(901, 'users/sign_in', window);
    logout_timer.start();

    // restart timer if activity
    $(document).on('keyup keypress blur change mousemove',function(){
      logout_timer.start();
    });

});

timer.js

Timer = function(time_in_secs, path, windowobj) {  // window object must be injected, else location replace will fail specs
  var self = this;    // 'this' not avail in setInterval, must set to local var avail to all functions
  this.state = 'init'
  this.time_remaining = time_in_secs;
  this.timer_id = undefined;

  this.start = function() {
    // if restarting, there will be a timer id.  Clear it to prevent creating a new timer, reset time remaining
    if (this.timer_id !== undefined) {
      this.time_remaining = time_in_secs;
      this.clear_timer(this.timer_id, self); 
    }
    this.state = 'running';

    this.timer_id = setInterval(function() {    // IE any version does not allow args to setInterval.  Therefore, local variables or refer to self obj
      self.time_remaining -= 1;

      // log status every 10 seconds
      if ((self.time_remaining % 10) === 0) {
        console.log("logging user out in " + self.time_remaining + " seconds");
      }

      // when timer runs out, clear timer and redirect
      if ( self.time_remaining <= 0 ) {
        self.clear_timer(self.timer_id, self);
        self.do_redirect(path, windowobj);
      };


    }, 1000);
    return this.timer_id;
  };

  this.clear_timer = function(timer_id, self) {
    self.state = 'stopped';
    clearInterval(self.timer_id);
  }

  this.remaining = function() {
    return this.time_remaining;
  };

  this.do_redirect = function(path, windowobj) {
    console.log("Redirecting to " + path);
    self.state = 'redirecting';
    windowobj.location = path;
  }
}

关于javascript - 在使用 Javascript 设计注销后自动重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19862502/

相关文章:

php - 使用Youtube API获取JSON时,使用哪个IP?托管的还是用户的?

ruby-on-rails - Rails : Requiring "RMagick" is deprecated. 使用 "rmagick"代替。FactoryGirl

ruby-on-rails - 为什么使用身份验证 token 而不是正常的身份验证过程?

javascript - 从另一个页面触发 button.click 事件

Javascript 在 Onsen UI 的模板中不起作用

ruby-on-rails - 如何从 Ruby 1.9.2 降级到 Ruby 1.8.7 以运行 Rails 2.0.2

ruby-on-rails - Sunspot Rails :text an :string type fields之间的区别

ruby-on-rails - 设计不使用 rails 。 (未定义的局部变量或方法 `‘devise’ ' 对于 Gemfile)

ruby-on-rails - 设计身份验证 gem : How to save the logged in user id?

javascript - 如何使用继承类中的方法