Problem saving information in localstorage via js

1

html

 <div id="timer">
          <span id="minutes"></span>:<span id="seconds"></span>
        </div>

JS

window.onload = function() {
  var access = localStorage.getItem('firstAccess');

  if(access == '') {
    var d = new Date();
    console.log(d);
    var time = localStorage.setItem('firstAccess', JSON.stringify(d));
    setTimer(time);
  }
  else {
     setTimer(access);     
  }
 function setTimer(time) {
     var timespan = countdown(time).toString();
     $('#minutes').html(timespan.minutes);
     $('#seconds').html(timespan.seconds);
 }
}

Console:

HereiswherethenameoftheItemsetthatisfirstAccessshouldappear

    
asked by anonymous 17.10.2017 / 18:34

2 answers

3

You're doing it wrong. in this if

 if(access == '') {
    var d = new Date();
    console.log(d);
    var time = localStorage.setItem('firstAccess', JSON.stringify(d));
    setTimer(time);
  }

Switch to this

 if(!access) {
    var d = new Date();
    console.log(d);
    localStorage.setItem('firstAccess', JSON.stringify(d));
    var time = localStorage.firstAccess
    setTimer(time);
  }
    
17.10.2017 / 18:42
3

Change the line:

if(access == '') {

To:

if(access == null) {

This is the default return value of the localStorage.getItem() method for an unpopulated key.

    
17.10.2017 / 18:47