简体   繁体   中英

get and set session variable in javascript

I have a common script included on every page, which initialize idletime variable to 0 as as soon as user logs in, and increment it after every 30 seconds, for which i have function written which is working fine, but after incrementing that variable i have to set that value to some session level variable so that on every page refresh this function increment should get that incremented value.Please find the code below

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

Sounds like you want web storage , specifically sessionStorage , which has excellent support (basically, it's on everything even vaguely recent [even IE8] except 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;

Having said that, if your goal is to click the logout link after 10 minutes of inactivity, it seems like it could be a bit simpler:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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