gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:37:36 25 4
gpt4 key购买 nike

我有一个要求,如果用户闲置一段时间,我必须注销用户。我正在使用 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);
}
}
})

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

<body ng-app="myApp" idle>

演示

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

关于angularjs - 如果在浏览器中打开多个选项卡/窗口,则会出现 ng-idle 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23414691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com