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

get and set session variable in javascript

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

<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 storage, specifically sessionStorage, which has excellent support(基本上,它出现在所有东西上,甚至是最近的 [甚至是 IE8],除了 Opera Mini)。

// 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 分钟不活动后单击注销 link,似乎可以更简单一些:

$(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();
    });
});