Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
localStorage.removeItem not working properly . How can i fix it?

I have this code for saving data from 2 inputs. Everything is all right when the page refreshes twice (the data is saved) but on third one the date disappear. I know this is because of the localStorage.removeItem, but I need the data to disappear after the tab is gone.

I use the same method for other stuff and it's working perfect. but in this case it's how I said , working for just 2 refreshes .

<input type="date" id="exdated" name="" 
        onfocus="localStorage.setItem('myTestApp','exdated')" 
        onkeyup="saveValue(this);">
<br><br> 
<input type="date" id="datata" name="" 
        onfocus="localStorage.setItem('myTestApp','datata')" 
        onkeyup="saveValue(this);">
<br><br>
let today = new Date().toISOString().slice(0, 10)

document.getElementById("datata").value = getSavedValue("datata"); 
document.getElementById("exdated").value = getSavedValue("exdated"); 

function saveValue(e) {
    var id = e.id;  
    var val = e.value; 
 
    localStorage.setItem(id, val); 
}

function getSavedValue  (v) {
    if (!localStorage.getItem(v)) {
      return today;
    }

    var itemcheta = localStorage.getItem(v);
    localStorage.removeItem(v); 
    
    return itemcheta;
}
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Since you want the data to disappear when the browser tab closes, you should use sessionStorage instead of localStorage. This will let the browser handle the correct removal of the data when the browsing session closes, so it's less code to worry about.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You have onfocus and onkeyup events that load/save the data and on load these two lines initiate it:

document.getElementById("datata").value = getSavedValue("datata"); 
document.getElementById("exdated").value = getSavedValue("exdated");

Tab or window close can be handled by a beforeunload event

window.addEventListener('beforeunload', function (e) {
    //Do some stuff
});

which you can use in order to handle tab/window close or the load of another page in the tab. However, this will run even if you reload the page in the tab. Another problem is that you might have other tabs opened and pointing to the same page as well.

So, how could one cope with this?

Due to the fact that your Javascript code can be found by any developer opening your page in your browser, encoding the value and decoding via Javascript is not really an option. You could use sessionStorage, like others suggested, but that will not work well in the case when you close your tab, open another tab and load the page again.

In my opinion at the point when the resources are unloaded, you cannot know for sure whether it's a tab closing, a reloading, navigation to another website or window closing. As a result, you need to delegate the logic that determines whether the item is to be removed from the storage to the page load.

So, something like this function may help you at page load:

function handleStorage() {
    let date = new Date(localStorage.getItem('savetime'));
    if ((date.getTime()) && ((new Date() - date) / 60000 > 5)) { //5 minutes
        localStorage.removeItem('datadata');
        localStorage.removeItem('exdated');
    }
}

So, no matter how many tabs you have where this page is opened, if at page load the last save is older than a certain amount of time, 5 minutes (you can decrease this time if it is more convenient that way), for instance, then you clear the saved data. Naturally, at saveValue you will need to save the date as well:

function saveValue(e) {
    var id = e.id;  
    var val = e.value; 
 
    localStorage.setItem(id, val);
    localStorage.setItem('savetime', new Date());
}

and then you can remove the localStorage.removeItem call from getSavedValue, where it's inappropriate anyway, since you may need to get the value multiple times for some reason.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You have to use onchange="saveValue(this);" and not onkeyup="saveValue(this);"

Demo / Note localStorage does not work on Stack Overflow

<input type="date" id="exdated" name="" onfocus="localStorage.setItem('myTestApp','exdated')" onchange="saveValue(this);">
<br><br>
<input type="date" id="datata" name="" onfocus="localStorage.setItem('myTestApp','datata')" onchange="saveValue(this);">
<br><br>
<script>
  let today = new Date().toISOString().slice(0, 10)

  document.getElementById("datata").value = getSavedValue("datata");
  document.getElementById("exdated").value = getSavedValue("exdated");

  function saveValue(e) {
    var id = e.id;
    var val = e.value;

    localStorage.setItem(id, val);
    console.log(localStorage)
  }

  function getSavedValue(v) {
    if (!localStorage.getItem(v)) {
      return today;
    }

    var itemcheta = localStorage.getItem(v);
    localStorage.removeItem(v);

    return itemcheta;
  }

</script>

JS-fiddle demo

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda