How to store objects in HTML5 localStorage/sessionStorage?
Using HTML5 LocalStorage and SessionStorage for Storing Objects
The HTML5 Web Storage API allows web applications to access local storage and session storage data from the browser. This can be used to store objects such as strings and numbers in the browser’s memory. In this article, we’ll explore how to use local storage and session storage to store objects in HTML5.
What Are LocalStorage and SessionStorage?
LocalStorage and SessionStorage are two different types of web storage available in HTML5. LocalStorage stores data in the user’s browser indefinitely, until the user clears their browsing data. SessionStorage stores data in the user’s browser until the browser window or tab closes.
Storing Objects in LocalStorage
To store an object in LocalStorage, you can convert it to a string using the built-in JavaScript function JSON.stringify(). You can then use the setItem() function to save the stringified object in LocalStorage. Here’s an example of storing a simple object in LocalStorage:
let myObject = {name: 'Bob', age: 27};
localStorage.setItem('object', JSON.stringify(myObject));
Retrieving Objects from LocalStorage
To retrieve an object from LocalStorage, you can use the getItem() function to get the stringified object, then use the built-in JavaScript function JSON.parse() to convert the string back into an object. Here’s an example of retrieving an object from LocalStorage:
let myObjectString = localStorage.getItem('object');
let myObject = JSON.parse(myObjectString);
Storing Objects in SessionStorage
To store an object in SessionStorage, you can convert it to a string using the built-in JavaScript function JSON.stringify(). You can then use the setItem() function to save the stringified object in SessionStorage. Here’s an example of storing a simple object in SessionStorage:
let myObject = {name: 'Bob', age: 27};
sessionStorage.setItem('object', JSON.stringify(myObject));
Retrieving Objects from SessionStorage
To retrieve an object from SessionStorage, you can use the getItem() function to get the stringified object, then use the built-in JavaScript function JSON.parse() to convert the string back into an object. Here’s an example of retrieving an object from SessionStorage:
let myObjectString = sessionStorage.getItem('object');
let myObject = JSON.parse(myObjectString);
Conclusion
Using LocalStorage and SessionStorage, you can easily store objects in HTML5. You can use the built-in JavaScript functions JSON.stringify() and JSON.parse() to convert objects to and from strings that can be stored in the browser’s memory.