Expiry of sessionStorage

前端 未结 4 2189
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 17:33

I am building a form in which i have to store the data in html5\'s sessionStorage i don\'t know where the sessionStorage expires. Can anyone tell m

4条回答
  •  再見小時候
    2020-12-13 17:50

    You can add some kind of expiration mechanism with something like this :

    // get from session (if the value expired it is destroyed)
    function sessionGet(key) {
      let stringValue = window.sessionStorage.getItem(key)
        if (stringValue !== null) {
          let value = JSON.parse(stringValue)
            let expirationDate = new Date(value.expirationDate)
            if (expirationDate > new Date()) {
              return value.value
            } else {
              window.sessionStorage.removeItem(key)
            }
        }
        return null
    }
    
    // add into session
    function sessionSet(key, value, expirationInMin = 10) {
      let expirationDate = new Date(new Date().getTime() + (60000 * expirationInMin))
        let newValue = {
        value: value,
        expirationDate: expirationDate.toISOString()
      }
      window.sessionStorage.setItem(key, JSON.stringify(newValue))
    }
    

提交回复
热议问题