Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

175
Visualizações
Set/Remove localStorage item and EventListener

I have been messing with localStorage and EventListener as seen below (from w3schools but with my messing around). The below always prints "A change was made in the storage area 3" to the div. I'm guessing this is the asynchronous nature of JS and I'd have to do something like promise chaining?

Secondly, and similarly, when I add removing the variable from localStorage and therefore, in EventListener, detecting that the variable is null, the below will not print anything to the div. i'm presuming it's seeing the removal before it can execute the first event (setting the variable) where it actually prints. Anyway, is there a way to pull off setting and removing a variable from localStorage or is this all that asynch stuff and needs promises (formerly callbacks and setTimeouts)? Thank you very much.

<button onclick="changeValue()">Change a Storage Item</button>

<p id="demo"></p>

<script>

    window.addEventListener("storage", myFunction);
    var x;
    var c=0;
    var mtv;
    function myFunction(event) {
      if (event.key==="mytime") {
        mtv=localStorage.getItem("mytime");
          if (mtv===null) {

            } else {
      document.getElementById("demo").innerHTML = "A change was made in the storage area "+ c;
          }
        }
    }

    function changeValue() {
      x = window.open("", "myWindow", "width=200,height=100");
      c=c+1
      x.localStorage.setItem("mytime", "true");
      c=c+1;
      x.localStorage.removeItem("mytime");
      c=c+1;
      x.close();
    }
</script>
</body>
</html>

UPDATE...I don't know how to format code in a response but instead of doing the above instant removal of the localStorage object, I went with an add/remove toggle on the localStorage variable...the adding or removal should trigger the ActionListener event in the grandparent window....

if(localStorage.getItem('mytime')){
      x.localStorage.removeItem("mytime");
}else{
      x.localStorage.setItem("mytime", "true");
}
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

Ok, the easier that you can do to see what happen is create an HTML with your code and open in your browser. Then, put breakpoints in the event and in the places in which you update the storage. Let's see:

  • Click on button
  • Open a window (useless because that window do nothing)
  • Update the storage (no event fire yet)
  • Remove the storage (no event fire yet)
  • Close the window
  • Now, you receive the 2 events with your c=3 in both cases

If you need track your c values, you can save in the storage that values:

x.localStorage.setItem("mytime", c);

Then, you receive a first event with event.newValue="1" and a second one with event.newValue=null and event.oldValue="1".

about 4 years ago · Santiago Gelvez Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda