How to store variable in JavaScript until reloading page?

0

My question is based solely on whether there is the possibility of entering a variable through a prompt() and that it is saved no matter how many times the code is run afterwards, and it is deleted only when the page is reloaded or manually deleted with other user interaction. What I really want is that if the variable is introduced for the first time, it does not need to ask the user for it.

I have dealt with sessionStorage() that due to lack of experience I do not conclude if it is my fault and I do not use it or I can not. And using something like if (variableX === null){ variableX = prompt("Introduzca el nombre.");} (it's just an example), but nothing gives me results. then I leave an example code.

The idea is that each time the button is pressed the variable "name" is saved and reused the next time when executing trigger() .

function trigger() {

  var nombre = prompt("Introduce tu nombre");

  var suma = 0;

  document.getElementById("expl").innerHTML = " ";

  do {

  var number = prompt("Introduzca un numero para la suma.");

  console.log(number);

  if (Number(number) == number) {

    number = Number(number);
    suma = suma + number;
    console.log(suma);

  }else {

    if (number != null){

      var hola = alert(number + " No es un nuemero valido.");
      console.log(hola);

    }

  }

} while (number != null);

  document.getElementById("expl").innerHTML += nombre + ", el resultado es: " + suma;

}
<button onClick="trigger()">Haz clck para empezar</button>
<p>Click en cancelar para ver la suma</p>
<p id="expl"></p>
    
asked by Dєηyη Crawford 12.08.2018 в 09:22
source

1 answer

2

You can use cookies, unlike sessionStorage, which is deleted when the session ends, that is when you close the browser or the tab; the cookies can store them with a period that you establish until their later destruction.

create a cookie (max-age are seconds)

document.cookie = "nombre=variableValor; max-age=7200";

To read a cookie there are different ways, I usually use this function with regular expressions

function readCookie(name) {

  return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\s*" + name.replace(/[\-\.\+\*]/g, "\$&") + "\s*\=\s*([^;]*).*$)|^.*$"), "$1")) || null;

}
    
answered by 12.08.2018 / 12:05
source