Edgars Edgars - 9 months ago 56
Javascript Question

localStorage is deleted after I use BACK button (All browsers)

I have implemented localStorage for some data that is useful for user experience, but is NOT essential for application itself (doesn't break functionality).

Problem: Every time I go to show page and then press BACK button to INDEX page all my local storage disappears.

localStorage is set in INDEX page with function:

$(document).ready(function () {
return $(".sort_link").on("ajax:success", function(e, data, status, xhr) {

localStorage.removeItem('results'); //removes any old localStorage values

if (document.getElementById("results-dupl")) {

var results = $("#results-dupl").html();
localStorage.results = results

} else {

var results = $("#searc_re").html();
localStorage.results = results

}).on("ajax:error", function(e, xhr, status, error) {



Basically, localStorage key is set independently, NOT before leaving current INDEX page.

Problem doesn't occur if I press any other link that redirects to INDEX page. I have tried and the same problem occurs on Firefox and Chrome so I guess - on all browsers.

What I have tried:

1) Added
right after setting localStorage key as seen in other question.

2) Double checked that above seen function actually creates localStorage key- Yes, 100 % creates.

3) It seems that also cookie that is created within the same INDEX page is lost after visiting show page and then with "BACK" button getting back to INDEX page.

Thanks in advance for any help.


Found solution based on accepted answer.

Basically, somehow previously commented out script was working and deleting localStorage and cookies:

document.cookie = "menu_storage=; expires=Thu, 01 Jan 1970 00:00:00 UTC";

Answer Source

Do not use localStorage.removeItem('results');. it'll fix the problem and localStorage.removeItem('results'); is useless anyway in this case because you can edit localStorage instead of deleting it.