Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sessionStorage is gone when browser is refreshed - Javascript

I am trying to keep some data in sessionStorage, but if I refresh the page or leave from a link then come back, the sessionStorage no longer exists.

I am new to sessionStorage, so sorry if this is an obvious fix.

Essentially I store an array into the sessionStorage.

  $scope.addPlant = function(plant) {
    for (i = 0; i < $scope.userPlantList.length; i++) {
      if ($scope.userPlantList[i] === plant) {
        alert("You have already added this plant");
        return;
      }
    }
    $scope.userPlantList.push($scope.currentPlant);
    sessionStorage.setItem("Plants",JSON.stringify($scope.userPlantList));
  };

And then when I want to see what is all stored

  $scope.retreiveList = function() {
    var retrieved = sessionStorage.getItem("Plants");
    $scope.userPlantList = JSON.parse(retrieved);
  }

And this works fine when I do not refresh the page/app at all.

Question: How can I get my sessionStorage to last during a refresh/immediate re-visit?

like image 419
Austin Avatar asked Mar 04 '15 17:03

Austin


People also ask

Is sessionStorage lost on refresh?

The sessionStorage object stores data only for a session. It means that the data stored in the sessionStorage will be deleted when the browser is closed. A page session lasts as long as the web browser is open and survives over the page refresh.

When session storage is cleared?

Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window. Session storage is the same as local storage but the only difference is that data stored in session storage will clear automatically once the page session will expire.

Does session storage persist?

localStorage and sessionStorage are almost identical and have the same API. The difference is that with sessionStorage , the data is persisted only until the window or tab is closed.

Does sessionStorage clear on tab close?

The sessionStorage object stores data for only one session. (The data is deleted when the browser is closed).


Video Answer


2 Answers

Check if the data are really gone by looking at the developer tools

If you using chrome: F12 -> Resources tab -> Session Storage.

sessionStorage lives with the browser tab. whenever you close a tab the sessionstorage data will be wiped out.

if you want something that will be shared across tabs, look for localStorage.

like image 95
alsafoo Avatar answered Oct 10 '22 21:10

alsafoo


I would recommend using the $window provider from angular

// set
$window.sessionStorage.setItem('Plants', angular.toJson($scope.userPlantList));
// get
$scope.userPlantList = angular.fromJson($window.sessionStorage.getItem('Plants')) || [];
like image 35
Kieran Avatar answered Oct 10 '22 21:10

Kieran