繁体   English   中英

在javascript中获取并设置会话变量

[英]get and set session variable in javascript

我在每个页面上都有一个通用脚本,该脚本在用户登录后立即将idletime变量初始化为0,并在每30秒后将其递增一次,为此我编写了运行良好的函数,但是在递增该变量后,将该值设置为某个会话级别变量,以便在每次刷新页面时此函数增量都应获得该增量值。请找到以下代码

<script type="text/javascript">
var timeOut=600000;//This is timeout value in miliseconds
    var idleTime = 0; // we shud get the incremented value on everypage refresh for this variable
    $(document).ready(function () {
     //Increment the idle time counter every minute.
    var idleInterval = setInterval(timerIncrement, 30000); //30seconds
});

function timerIncrement() {
idleTime = idleTime + .5;//incrementing the counter by 30 seconds
var timeout= timeOut/60000;
if (idleTime > (timeout-2)) { 
    document.getElementById('logoutLink').click();
}
}
</script>

听起来好像您想要Web存储 ,特别是sessionStorage ,它具有出色的支持 (基本上,除了Opera Mini之外,它甚至在最近的所有版本[甚至IE8]上都存在)。

// On page load (note that it's a string or `undefined`):
var idleTime = parseFloat(sessionStorage.idleTime || "0");

// When updating it (it will automatically be converted to a string):
sessionStorage.idleTime = idleTime += .5;

话虽如此,如果您的目标是在闲置10分钟后单击注销链接,则看起来可能会更简单一些:

$(document).ready(function() {
    var lastActivity = parseInt(sessionStorage.lastActivity || "0") || Date.now();
    setInterval(function() {
        if (Date.now() - lastActivity > 600000) { // 600000 = 10 minutes in ms
            document.getElementById('logoutLink').click();
        }
    }, 30000);

    // In response to the user doing anything (I assume you're setting
    // idleTime to 0 when the user does something
    $(/*....*/).on(/*...*/, function() {
        sessionStorage.lastActivity = lastActivity = Date.now();
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM