localStorage不存储更新的值

时间:2018-12-29 11:24:49

标签: javascript local-storage

我正在编写一个脚本,以使用户知道刷新页面之前花了多少时间。为此,我使用setInterval函数增加了一个计时器,并通过localStorage将数据存储在浏览器中。页面刷新后,我将检索存储的数据并显示它们。同时,计时器返回到0,然后再次开始递增。

不幸的是,我的脚本出了点问题,因为localStorage不存储更新的时间值(始终为-1)。我的脚本怎么了?

//TimeSpent = -1, so setInterval sets it to 0s instead of 1s when the page opens. 
var timeSpent = -1

//Update time every second
var timer = setInterval(()=>{
    timeSpent +=1;
    }, 1000);

//If first visit, ask to refresh. Else, display timeSpent on previous page by retrieving localStorage data.
function start(){
  if (localStorage.timeData){
  var timerJson = localStorage.getItem("timeData");
  var timerParsed = JSON.parse(timerJson);
  console.log(`You spent ${timerParsed.time} seconds on previous page`)
  }
  else{
  console.log("Reload the page and see how much time you spent reading this.")
  }
}

//Trig function when page opens.
window.onload = start();

//Before page reloads, store timeSpent in localStorage as a Json file.
   var timeData = {
   time: timeSpent, 
   }

  function storeData (timeData){
  var timerJson = JSON.stringify(timeData) 
  localStorage.setItem("timeData", timerJson);
  }

window.onbeforeunload = storeData (timeData) 

谢谢!

3 个答案:

答案 0 :(得分:1)

window.onbeforeunload必须具有类型function的值,但是在您的代码中它是undefined。因此,您应该将其更改为:

window.onbeforeunload = function storeData (){
  var timerJson = JSON.stringify(timeData) 
  localStorage.setItem("timeData", timerJson);
  }

我还从函数中删除了该参数,使其成为闭包。

UPD。正如乔纳斯·威尔姆斯(Jonas Wilms)指出的那样,您应该执行相同的onload事件和start函数。

也。为了始终获得timeSpent的实际(新)值,您应该这样做:

const state = {timeSpent: -1}

随处可见,将timeSpent替换为state.timeSpent

这样,闭包将具有指向state对象的链接,而不仅仅是获取原始timeSpent的初始值。

答案 1 :(得分:0)

此代码对我来说效果很好:

let timeData = {
time: -1
}
timeData.time = setInterval(()=>{
    timeData.time += 1 
    console.log(timeData.time)
  }, 1000);
function start(){
  if (localStorage.timeData){
  var timerJson = localStorage.getItem("timeData");
  var timerParsed = JSON.parse(timerJson);
  console.log(`You spent ${timerParsed.time} seconds on previous page`)
  }
  else{
  console.log("Reload the page and see how much time you spent reading this.")
  }
}
window.onload = start();
window.onbeforeunload = function () {
  var timerJson = JSON.stringify(timeData) 
  localStorage.setItem("timeData", timerJson);
}

答案 2 :(得分:0)

我假设您在本地进行测试。由于本地存储的存储方式类似于基于Cookie的域(并且在本地测试脚本时没有域),因此根本不会保存数据。

In HTML5, is the localStorage object isolated per page/domain?

编辑:在本地,我的意思是不使用网络服务器的简单HTML文件。

相关问题