刷新浏览器时 sessionStorage 消失了 - Javascript

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28861357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:40:10  来源:igfitidea点击:

sessionStorage is gone when browser is refreshed - Javascript

javascriptangularjslocal-storagesession-storage

提问by Austin

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.

我试图在 sessionStorage 中保留一些数据,但是如果我刷新页面或从链接离开然后回来,则 sessionStorage 不再存在。

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

我是 sessionStorage 的新手,很抱歉,如果这是一个明显的修复。

Essentially I store an array into the sessionStorage.

本质上,我将一个数组存储到 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?

问题:如何在刷新/立即重新访问期间使我的 sessionStorage 持续下去?

回答by alsafoo

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

通过查看开发人员工具检查数据是否真的消失了

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

如果您使用 chrome:F12 -> 资源选项卡 -> 会话存储。

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

sessionStorage 与浏览器选项卡一起存在。每当您关闭选项卡时,会话存储数据将被清除。

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

如果您想要跨选项卡共享的内容,请查找 localStorage。

回答by Kieran

I would recommend using the $windowprovider from angular

我建议$window从 angular使用提供程序

// set
$window.sessionStorage.setItem('Plants', angular.toJson($scope.userPlantList));
// get
$scope.userPlantList = angular.fromJson($window.sessionStorage.getItem('Plants')) || [];