簡體   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