How to make Local Storage expire?

Asked

Viewed 7,003 times

9

I have a certain scenario in which I need the user to stay login and stay connected for some time. However, if inactivity is detected on the page after a while, maybe 20 min, expire the Local Storage invalidating the saved information.

To set a value for an item I use the following code:

localStorage.setItem('login', true);

This way, the intention is to keep the user connected until they do logout manually using the code below:

localStorage.removeItem('login'); 

How to make the Local Storage expires after a certain downtime?

3 answers

11


I would say that if the values are that simple, document.cookie I would, but you can still do it like localStorage, what you can do is create a vector in json format (maybe) and set a date to limit it.

And at the beginning of the page, first of all (not even onload needs) add something like:

function localStorageExpires()
{
    var toRemove = [],                      //Itens para serem removidos
        currentDate = new Date().getTime(); //Data atual em milissegundos

    for (var i = 0, j = localStorage.length; i < j; i++) {
       var key = localStorage.key(i),
           itemValue = localStorage.getItem(key);

       //Verifica se o formato do item para evitar conflitar com outras aplicações
       if (itemValue && /^\{(.*?)\}$/.test(itemValue)) {

            //Decodifica de volta para JSON
            var current = JSON.parse(itemValue);

            //Checa a chave expires do item especifico se for mais antigo que a data atual ele salva no array
            if (current.expires && current.expires <= currentDate) {
                toRemove.push(key);
            }
       }
    }

    // Remove itens que já passaram do tempo
    // Se remover no primeiro loop isto poderia afetar a ordem,
    // pois quando se remove um item geralmente o objeto ou array são reordenados
    for (var i = toRemove.length - 1; i >= 0; i--) {
        localStorage.removeItem(toRemove[i]);
    }
}

localStorageExpires();//Auto executa a limpeza

/**
 * Função para adicionar itens no localStorage
 * @param {string} chave Chave que será usada para obter o valor posteriormente
 * @param {*} valor Quase qualquer tipo de valor pode ser adicionado, desde que não falhe no JSON.stringify
 * @param {number} minutos Tempo de vida do item
 */
function setLocalStorage(chave, valor, minutos)
{
    var expirarem = new Date().getTime() + (60000 * minutos);

    localStorage.setItem(chave, JSON.stringify({
        "value": valor,
        "expires": expirarem
    }));
}

/**
 * Função para obter itens do localStorage que ainda não expiraram
 * @param {string} chave Chave para obter o valor associado
 * @return {*} Retorna qualquer valor, se o item tiver expirado irá retorna undefined
 */
function getLocalStorage(chave)
{
    localStorageExpires();//Limpa itens

    var itemValue = localStorage.getItem(chave);

    if (itemValue && /^\{(.*?)\}$/.test(itemValue)) {

        //Decodifica de volta para JSON
        var current = JSON.parse(itemValue);

        return current.value;
    }
}

To use call like that:

//login é tua chave, true é teu valor e 25 são os minutos de vida
setLocalStorage('login', true, 25);

To catch use:

var login = getLocalStorage('login');

alert(login);
  • Congratulations on the approach. Please update the setLocalStorage function. One parenthesis is missing from the setItem statement.

  • Dear @jeff_drumgod thank you very much. Already adjust ;)

  • @jeff_drumgod thank you!

1

One way to accomplish this would be to add on the screen a function that validates mouse and key activities with a counter every minute, if it doesn’t make any movement in that 20 minute period it can remove its Storage location:

Follow the code in Jquery:

<script>
var tempo = 0;

$(document).ready(function () {
    //Valida  o Tempo incrementando o valor a cada 1 minuto, caso chegue a 20 sem atividade será eliminada
    var idleInterval = setInterval(ValidaTempo, 60000); // 60000 =  1 minuto

    //Caso o usuário mova o mouse na aplicação zera o contador
    $(this).mousemove(function (e) {
        tempo = 0;
    });
      //Caso o usuário pressione qualquer tecla na aplicação zera o contador
    $(this).keypress(function (e) {
        tempo = 0;
    });
});
//Função que acrescenta ao contador a cada minuto sem atividade e eliminando a local storage.
function ValidaTempo() {
    //Acrescenta cada minuto sem atividade
    tempo = tempo + 1;
    //Caso o tempo seja maior que 19 minutos ele encerra a sessão 
    if (tempo > 19) { // 20 minutos
        localStorage.removeItem('login'); 
        //redireciona login
    }
}

I hope it might have helped. ;)

  • From what I understand, that code only works if my page is open. If I log in and leave the page, if I come back after a while you will not have removed the localStorage item. May not fully solve the problem.

  • @Acklay, for this case it would not be better to change your approach instead of localstorage to sessionStorage ?

0

Unfortunately there is no attribute to remove the localStorage item when it expires.

There are different ways to do this, if you are using Angularjs 1.X you can do something like this:

app.run(function($interval){
  $interval( function(){
    delete localStorage[key];
    //remove todos os objetos com a 'key' informada.
  }, 1000*60*20);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.