Save Javascript objects in sessionStorage

后端 未结 9 639
抹茶落季
抹茶落季 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

    Either you can use the accessors provided by the Web Storage API or you could write a wrapper/adapter. From your stated issue with defineGetter/defineSetter is sounds like writing a wrapper/adapter is too much work for you.

    I honestly don't know what to tell you. Maybe you could reevaluate your opinion of what is a "ridiculous limitation". The Web Storage API is just what it's supposed to be, a key/value store.

    0 讨论(0)
  • 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))
        };
    
    0 讨论(0)
  • 2020-12-02 05:21
        var user = {'name':'John'};
        sessionStorage['user'] = JSON.stringify(user);
        console.log(sessionStorage['user']);
    
    0 讨论(0)
  • 2020-12-02 05:23

    Session storage cannot support an arbitrary object because it may contain function literals (read closures) which cannot be reconstructed after a page reload.

    0 讨论(0)
  • 2020-12-02 05:34

    You could also use the store library which performs it for you with crossbrowser ability.

    example :

    // Store current user
    store.set('user', { name:'Marcus' })
    
    // Get current user
    store.get('user')
    
    // Remove current user
    store.remove('user')
    
    // Clear all keys
    store.clearAll()
    
    // Loop over all stored values
    store.each(function(value, key) {
        console.log(key, '==', value)
    })
    
    0 讨论(0)
  • 2020-12-02 05:40

    The solution is to stringify the object before calling setItem on the sessionStorage.

    var user = {'name':'John'};
    sessionStorage.setItem('user', JSON.stringify(user));
    var obj = JSON.parse(sessionStorage.user);
    
    0 讨论(0)
提交回复
热议问题