HTML5 introduced a new concept for data storage – Web Storage.
Web storage consists of two components: Session storage and Local storage.
Session storage is a temporary storage of information that is deleted after the browser is closed.
Local storage represents storage for data on an ongoing basis. Data from local storage is not automatically deleted and does not expire. This data is not sent to the server in an HTTP request.
In addition, the amount of local storage in Chrome and Firefox is 5 Mb for a domain, and in IE – 10 Mb.
All data in web storage is a set of key-value pairs. That is, each object has a unique key name and a certain value.
To work with local storage in JavaScript, the localStorage object is used, and to work with session storage, the sessionStorage object is used.
Save data
To save data, pass it to the setItem() method of the localStorage object:
localStorage.setItem("login", "Alex332");//the first parameter is the key, the second is the value of the object to be saved.
If localStorage already has an object with the “login” key, then its value is replaced with a new one.
Getting data
To get the saved data, you need to call the getItem() method. The object key is passed to this method:
var login = localStorage.getItem("login"); //Alex332
Delete data
To remove an object, use the removeItem() method, which takes the key of the object to be removed:
localStorage.removeItem("login");
And to completely remove all objects from localStorage, you can use the clear() method:
localStorage.clear();
Data in localStorage
Saving objects is simple, but keep in mind that the data in localStorage is stored as a string:
localStorage.setItem("age", 33); var age = localStorage.getItem("age"); age = parseInt(age) + 10; document.write(age); //33
If, in this case, the value is not converted to a number using parseInt(), then age will act as a string.
var user = { name: "Tom", age: 23, married: false }; localStorage.setItem("user", user); var savedUser = localStorage.getItem("user"); document.write(savedUser); //[object Object] document.write(savedUser.name); // undefined - savedUser - string, not a Object
In this case, we need to use JSON serialization:
var user = { name: "Tom", age: 23, married: false }; localStorage.setItem("user", JSON.stringify(user)); var savedUser = JSON.parse(localStorage.getItem("user")); document.write(savedUser.name + " " + savedUser.age + " " + savedUser.married);