首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在javascript中获取和设置会话变量

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

Stack Overflow用户
提问于 2016-01-04 09:24:45
回答 1查看 2.2K关注 0票数 0

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

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-01-04 09:28:37

听起来你想要web存储,特别是sessionStorage,它有极好的支持 (基本上,除了Opera Mini之外,几乎所有的东西都是最近出现的,甚至是IE8 )。

代码语言:javascript
复制
// 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分钟之后单击注销链接,那么它看起来可能会更简单一些:

代码语言:javascript
复制
$(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();
    });
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34587964

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档