Save Javascript objects in sessionStorage

后端 未结 9 766
抹茶落季
抹茶落季 2020-12-02 05:14

SessionStorage and LocalStorage allows to save key/value pairs in a web browser. The value must be a string, and save js objects is not trivial.

var user = {         


        
9条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 05:18

    Use case:

     sesssionStorage.setObj(1,{date:Date.now(),action:'save firstObject'});
     sesssionStorage.setObj(2,{date:Date.now(),action:'save 2nd object'}); 
     //Query first object
      sesssionStorage.getObj(1)
      //Retrieve date created of 2nd object
      new Date(sesssionStorage.getObj(1).date)
    

    API

    Storage.prototype.setObj = function(key, obj) {
    
            return this.setItem(key, JSON.stringify(obj))
        };
        
        Storage.prototype.getObj = function(key) {
            return JSON.parse(this.getItem(key))
        };
    

提交回复
热议问题