sessionStorage with expiry time

Asked

Viewed 651 times

1

I made a little script here, but I’m not getting a customization on it.

I need to set an expiration time for sessionStorage. Follows below the script:

<script type="text/javascript">
    if (sessionStorage){
    if ( ! sessionStorage.getItem('visualizado')){
    document.getElementById('inauguracao').style.display='block';
    sessionStorage.setItem( 'visualizado', 'verdadeiro' );}}
</script>

It will display an image to the user, and will hide if it has already been viewed, only I need it to be displayed again after a period of ex: 30 minutes.

It is possible to implement in this script?

3 answers

1

Instead of working with visualizado, you will need to work with hora.

So you can do the programming to validate how much time it should be displayed.

I removed your variable "viewable" and added the variable "time". Another tip is, you don’t need to have getItem and setItem for sessionStorage. You can work with it as a javascript object. In the example below, I put for every 10 seconds check if you need to display again and, I set it to be displayed every 1 minute. In your case, change the variable "minutes" to 30.

The code is commented, so I believe it’s easy to understand.

setInterval(function(){

    if (sessionStorage)
    {
        console.log('Iniciando...');

        // 30 Minutos
        var minutos = 1;

        // Calcula em milisegundos o tempo acima setado
        var mostrarEntre = 60 * minutos * 1000;

        // Resgata o valor da última exibição
        var exibidoUltimaVez = sessionStorage.tempoExibido * 1;
        var agora = + new Date();

        // Verifica se nunca exibiu ou, se neste momento já deve ser exibido de novo
        if(exibidoUltimaVez === null || agora >= (exibidoUltimaVez+mostrarEntre))
        {
            console.log("Exibindo em: %s", new Date())

            // Atualize para ter o valor da última vez exibida
            sessionStorage.tempoExibido = agora;

            document.getElementById('inauguracao').style.display='block';
        }
    }
}, 10000);

1

An initial reading that is interesting:

Differences between localStorage Vs sessionStorage?

If you want to persist the value between page sessions, you should use localStorage. From what I read, these values do not have, by default, how to set life time, so for your case, as the value in the record is not important, you can store the value of the timestamp and always check the amount of time that has passed from its creation to the current one in a new session. This check looks something like this:

// Verifica se existe o registro local:
if (localStorage.getItem("visualizado")) {

  // Recupera o timestamp atual:
  let now = Date.now();

  // Calcula a diferença entre o atual e o registro:
  let diff = now - localStorage.getItem("visualizado");

  // Define o tempo (ms) que durará o registro:
  let delay = 1*60*1000;

  // Se a diferença for maior que o tempo de duração:
  if (diff >= delay) {

    // Remove o registro:
    localStorage.removeItem("visualizado");

  } else {

    // Senão, exibe o tempo de vida restante (opcional):
    console.log("Você já visualizou a imagem no último minuto. Volte em " + (delay - diff)/1000 + "s.");

  }
}

The logic to display the image is basically the same, only changing the value persisted in the record:

// Se não existir o registro:
if (!localStorage.getItem("visualizado")) {

  // Exibe a imagem:
  console.log("Imagem foi exibida.");

  // Armazena o timestamp atual no registro:
  localStorage.setItem("visualizado", Date.now());

}

See working on Jsbin, for a time of 1 minute.

1

<script>
(function () {
 var minuto = 0;
 setInterval(function () {
   if (minuto == 30) {
      aviso();
     minuto = 0;
   } else {
     minuto += 10;
   }
 }, 600000);//10 minutos

 var aviso = function () {
   if (sessionStorage.getItem('visualizado') == '0') {
       document.getElementById('inauguracao').style.display = 'none';
       sessionStorage.setItem( 'visualizado', 1);
   } else {
     document.getElementById('inauguracao').style.display = 'block';
     sessionStorage.setItem( 'visualizado', 0);
   }
 }
})();
</script>

<div id="inauguracao" style="background-color: red;display: none">Teste</div>

That’s how it works.

Browser other questions tagged

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