Storing and Retrieving Objects in HTML5 Web Storage

HTML5 Web Storage provides two types of storage: localStorage and sessionStorage. Both types allow you to store key-value pairs, but they differ in their persistence and accessibility. In this tutorial, we will focus on storing and retrieving objects in HTML5 Web Storage.

Introduction to Web Storage

Web Storage is a client-side storage system that allows web applications to store data locally within the user’s browser. It consists of two storage types: localStorage and sessionStorage. The main difference between them is their persistence:

  • localStorage: Data stored in localStorage persists even after the user closes the browser or restarts their device.
  • sessionStorage: Data stored in sessionStorage is deleted when the user closes the browser.

Storing Objects

By default, Web Storage only supports storing strings. However, you can store objects by converting them to JSON strings using JSON.stringify(). Here’s an example:

// Create an object
var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Store the object in localStorage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from localStorage
var retrievedObject = JSON.parse(localStorage.getItem('testObject'));

console.log(retrievedObject); // Output: { one: 1, two: 2, three: 3 }

Extending Storage Prototype

To make storing and retrieving objects more convenient, you can extend the Storage prototype with custom methods. Here’s an example:

// Extend Storage prototype with setObject and getObject methods
Storage.prototype.setObject = function(key, value) {
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key) {
    var value = this.getItem(key);
    return value && JSON.parse(value);
}

With these custom methods, you can store and retrieve objects more easily:

// Store an object using setObject method
localStorage.setObject('testObject', { 'one': 1, 'two': 2, 'three': 3 });

// Retrieve the object using getObject method
var retrievedObject = localStorage.getObject('testObject');

console.log(retrievedObject); // Output: { one: 1, two: 2, three: 3 }

Handling Private Members and Circular References

When storing objects, you may encounter issues with private members or circular references. To handle these cases, you can use techniques like overwriting the toString() method or using a custom serialization function.

For example, to store an object with private members, you can overwrite its toString() method:

// Create an object with private and public members
function MyClass(privateContent, publicContent) {
    var privateMember = privateContent || 'defaultPrivateValue';
    this.publicMember = publicContent  || 'defaultPublicValue';

    this.toString = function() {
        return '{"private": "' + privateMember + '", "public": "' + this.publicMember + '"}';
    };
}

// Store the object
var obj = new MyClass('invisible', 'visible');
localStorage.object = obj.toString();

// Retrieve and parse the object
obj = JSON.parse(localStorage.object);

console.log(obj); // Output: { private: 'invisible', public: 'visible' }

To handle circular references, you can use a custom serialization function that replaces circular references with placeholders:

// Create an object with circular reference
var obj = { id: 1, sub: {} };
obj.sub.circular = obj;

// Define a custom serialization function
function serializeObject(value) {
    if (value === obj) {
        return '$ref' + value.id + '$';
    } else {
        return value;
    }
}

// Store the object with circular reference
localStorage.object = JSON.stringify(obj, serializeObject);

// Retrieve and parse the object
var retrievedObj = JSON.parse(localStorage.object);

console.log(retrievedObj); // Output: { id: 1, sub: { circular: '$ref1$' } }

Conclusion

Storing and retrieving objects in HTML5 Web Storage requires some additional steps, such as converting objects to JSON strings or using custom serialization functions. By extending the Storage prototype with custom methods and handling private members and circular references, you can make storing and retrieving objects more convenient and efficient.

Remember to always use JSON.stringify() and JSON.parse() when storing and retrieving objects, respectively, and consider using custom serialization functions for complex object structures.

Leave a Reply

Your email address will not be published. Required fields are marked *