加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – ng-idle问题,如果在浏览器中打开了多个选项卡/窗口

发布时间:2020-12-17 17:45:28 所属栏目:安全 来源:网络整理
导读:我有一个要求,如果它闲置一段时间我必须注销用户. 我正在使用ng-idle 0.3.2. 如果在浏览器中打开了多个选项卡/窗口,我会遇到问题.如果我正在使用选项卡,并且在我正在处理的活动选项卡上时未登录的选项卡仍然登录,因为它处于活动状态. 如何在我处理其他类似标
我有一个要求,如果它闲置一段时间我必须注销用户.
我正在使用ng-idle 0.3.2.

如果在浏览器中打开了多个选项卡/窗口,我会遇到问题.如果我正在使用选项卡,并且在我正在处理的活动选项卡上时未登录的选项卡仍然登录,因为它处于活动状态.

如何在我处理其他类似标签时阻止从非活动标签退出?

解决方法

摘要

使用localStorage在运行应用程序的任何选项卡中存储上次已知活动事件的时间戳.在正在运行的应用的每个实例中每隔几秒轮询一次该值.如果已更新,请重置ng-idle计时器以避免过早注销(或者在广播$idleTimeout事件时设置的任何操作).

如何

创建一个指令来体现上述行为:

.directive('idle',function($idle,$timeout,$interval){
  return {
    restrict: 'A',link: function(scope,elem,attrs) {
      var timeout;
      var timestamp = localStorage.lastEventTime;

      // Watch for the events set in ng-idle's options
      // If any of them fire (considering 500ms debounce),update localStorage.lastEventTime with a current timestamp
      elem.on($idle._options().events,function(){
        if (timeout) { $timeout.cancel(timeout); }
        timeout = $timeout(function(){
          localStorage.setItem('lastEventTime',new Date().getTime());
        },500);
      });

      // Every 5s,poll localStorage.lastEventTime to see if its value is greater than the timestamp set for the last known event
      // If it is,reset the ng-idle timer and update the last known event timestamp to the value found in localStorage
      $interval(function() {
        if (localStorage.lastEventTime > timestamp) {
          $idle.watch();
          timestamp = localStorage.lastEventTime;
        } 
      },5000);
    }
  }
})

将directive属性添加到body标记以确保检测到页面中的所有鼠标和键盘事件:

<body ng-app="myApp" idle>

演示

多个选项卡中的Open up and run this Plunk以及每个选项卡的控制台.将鼠标光标移动到正文内容上,并观察记录到两个控制台的事件.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读