app.run(function($rootScope) {
var lastDigestRun = new Date();
$rootScope.$watch(function detectIdle() {
var now = new Date();
if (now - lastDigestRun > 10*60*60) {
// logout here, like delete cookie, navigate to login ...
}
lastDigestRun = now;
});
});
angular.module('demo', ['ngIdle'])
// omitted for brevity
.config(function(IdleProvider, KeepaliveProvider) {
IdleProvider.idle(10*60); // 10 minutes idle
IdleProvider.timeout(30); // after 30 seconds idle, time the user out
KeepaliveProvider.interval(5*60); // 5 minute keep-alive ping
})
.run(function($rootScope) {
$rootScope.$on('IdleTimeout', function() {
// end their session and redirect to login
});
});
Ng-Idle 看起来是个不错的选择,但是我不能理解 Brian F 的修改,而且我也想超时到睡眠阶段,而且我脑子里有一个非常简单的用例。我把它缩减到下面的代码。它通过挂钩事件来重置超时标志(懒惰地放置在 $rootScope 中)。它只在用户返回(并触发事件)时检测超时发生,但这对我来说已经足够好了。我无法在这里获得棱角的 $location,但是使用 document.location.href 可以完成这项工作。
在. config 运行之后,我将这个命令插入到我的 app.js 中。
app.run(function($rootScope,$document)
{
var d = new Date();
var n = d.getTime(); //n in ms
$rootScope.idleEndTime = n+(20*60*1000); //set end time to 20 min from now
$document.find('body').on('mousemove keydown DOMMouseScroll mousewheel mousedown touchstart', checkAndResetIdle); //monitor events
function checkAndResetIdle() //user did something
{
var d = new Date();
var n = d.getTime(); //n in ms
if (n>$rootScope.idleEndTime)
{
$document.find('body').off('mousemove keydown DOMMouseScroll mousewheel mousedown touchstart'); //un-monitor events
//$location.search('IntendedURL',$location.absUrl()).path('/login'); //terminate by sending to login page
document.location.href = 'https://whatever.com/myapp/#/login';
alert('Session ended due to inactivity');
}
else
{
$rootScope.idleEndTime = n+(20*60*1000); //reset end time
}
}
});
angular.module('myModule', ['ActivityMonitor']);
MyController.$inject = ['ActivityMonitor'];
function MyController(ActivityMonitor) {
// how long (in seconds) until user is considered inactive
ActivityMonitor.options.inactive = 600;
ActivityMonitor.on('inactive', function() {
// user is considered inactive, logout etc.
});
ActivityMonitor.on('keepAlive', function() {
// items to keep alive in the background while user is active
});
ActivityMonitor.on('warning', function() {
// alert user when they're nearing inactivity
});
}