Web Storage, can store data locally within the user's browser.
1) Check Browser Support
Before using web storage, check browser support for localStorage and sessionStorage:
if (typeof(Storage) !== "undefined") {
// Code for localStorage/sessionStorage.
} else {
// Sorry! No Web Storage support..
}
2) To Store Data
Create a localStorage name/value pair with name="fname" and value="Steve"
localStorage.setItem("fname", "Steve");
OR
localStorage.fname = "Steve";
3) To Retrieve Data
Retrieve the value of "fname" and insert it into the element with id="result"
localStorage.getItem("fname");
OR
localStorage.fname;
4) Remove Storage Item
To remove the "fname" localStorage item
localStorage.removeItem("fname");
OR
delete localStorage.fname;
5) Clearing Storage
To Clear (delete) all stored data
localStorage.clear();
6) To Store Structured Data
To store structured data, you can use JSON to serialize it to and from strings for storage
var students = [{name: "Tyler", marks: 22}, {name: "Ryan", marks: 41}];
localStorage.setItem('students', JSON.stringify(students));
console.log(JSON.parse(localStorage.getItem('students')));
// [ Object { name: "Tyler", marks: 22 }, Object { name: "Ryan", marks: 41 } ]
7) Session Storage
The sessionStorage object implements the same Storage interface as localStorage. However, instead of being
shared with all pages from the same origin, sessionStorage data is stored separately for every window/tab.
- Save data to sessionStorage
sessionStorage.setItem('key', 'value');
- Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
- Remove saved data from sessionStorage
sessionStorage.removeItem('key')
8) Error Condition
When browsers are set to prevent cookies, they often block localStorage as well. This will lead to exception if you try to use it. Remember to handle these situations accordingly.
var video = document.querySelector('video')
try {
video.volume = localStorage.getItem('volume')
} catch (error) {
alert('If you\'d like your volume saved, turn on cookies')
}
video.play()
If you found this useful, consider:
ā Follow @iarchitsharma for more content like this
ā Follow me on Twitter