【问题标题】:Redirecting automatically after Devise log-out with Javascript?使用Javascript设计注销后自动重定向?
【发布时间】:2013-11-08 15:21:13
【问题描述】:

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

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

Devise wiki 似乎没有示例,是否有对此的标准解决方案?一个带有倒数计时器的 javascript 弹出窗口,如果用户没有点击“让我保持登录”,它会进行重定向?

【问题讨论】:

    标签: javascript ruby-on-rails devise


    【解决方案1】:

    我最终实现了类似于下面的 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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-10-23
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多