sessionStorage with expiration time

0

I made a small script here, but I'm not able to do a customization on it.

I need to set an expiration time for sessionStorage . Here is 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 for the user, and will hide if it has already been viewed, but it needs to be displayed again after a period of eg 30 minutes.

Is it possible to implement this script?

    
asked by anonymous 22.06.2017 / 20:03

3 answers

0

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

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

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

The code is commented on, so I think your understanding is easy.

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);
    
22.06.2017 / 20:36
0

An initial reading that is interesting:

Differences between localStorage Vs sessionStorage?

If you want the value between page sessions to persist, you should use localStorage . From what I read, these values do not have by default how to set the lifetime, so for your case, since the value in the record is not important, you can store the value of the current timestamp and always check the amount of time that has passed since its creation until 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, just changing the value persisted in the registry:

// 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 in the JSBin , for a time of 1 minute.

    
22.06.2017 / 20:39
0
<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.

    
22.06.2017 / 21:55