7

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;
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
stoperan
  • 31
  • 11

3 Answers3

6

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.

Alex Gyoshev
  • 11,929
  • 4
  • 44
  • 74
4

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.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
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

Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77
  • Hello Carsten , did you check to refresh the JS-fiddle demo more then once ? It's doing the same on the first refresh is alright on second one coming back to the default date :) – stoperan Sep 01 '21 at 12:39
  • @stoperan Yes it gives you the default date because you have `localStorage.removeItem(v);` after `var itemcheta = localStorage.getItem(v);`. Simple just remove `localStorage.removeItem(v);` and it will not clear it – Carsten Løvbo Andersen Sep 01 '21 at 12:40
  • yes my question is , how can i keep the localstorage.removeitem to be executed after tab closure or window closure . Not after refresh on second time :) – stoperan Sep 01 '21 at 12:43
  • @stoperan maybe you can use this to solve the problem, but clearing on tab closure is not an easy thing https://stackoverflow.com/questions/3888902/detect-browser-or-tab-closing – Carsten Løvbo Andersen Sep 01 '21 at 13:04