9

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?

12
  • @JonathanLonowski Refreshing a page don't close the session. So the issue is somewhere else Mar 4, 2015 at 17:54
  • 3
    Are you sure that on refresh, your script don't erase the data ? Mar 4, 2015 at 17:55
  • Is any of your code asynchronous? Mar 4, 2015 at 17:56
  • 3
    @Austin Go to the developer tools and make sure your data are gone from sessionStorage. If you using chrome: F12 -> Resources tab -> Session Storage.
    – alsafoo
    Mar 4, 2015 at 18:04
  • 2
    @alsafoo whoooaa they do exist! So...what am I doing wrong in my access statement? Are they lost out of my scope or something?
    – Austin
    Mar 4, 2015 at 18:07

2 Answers 2

11

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.

1

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')) || [];
3
  • 1
    Angular wasn't mentioned in the question above, how about just using the window object?
    – MiFiHiBye
    Aug 17, 2020 at 18:44
  • 5
    angularjs is in the tags list
    – Kieran
    Aug 18, 2020 at 2:04
  • 1
    Good catch reading tags. ^voted. Mar 20, 2022 at 18:50

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.