The Storage
interface of the Web Storage API provides access to the session storage or local storage for a particular domain, allowing you to for example add, modify or delete stored data items.
If you want to manipulate the session storage for a domain, you call {{domxref("WindowSessionStorage.sessionStorage")}} method; If you want to manipulate the local storage for a domain, you call {{domxref("WindowLocalStorage.localStorage")}}.
Properties
- {{domxref("Storage.length")}} {{readonlyInline}}
-
Returns an integer representing the number of data items stored in the
Storage
object.
Methods
- {{domxref("Storage.key()")}} {{readonlyInline}}
- When passed a number n, this method will return the name of the nth key in the storage.
- {{domxref("Storage.getItem()")}} {{readonlyInline}}
- When passed a key name, will return that key's value.
- {{domxref("Storage.setItem()")}} {{readonlyInline}}
- When passed a key name and value, will add that key to the storage, or update that key's value if it already exists.
- {{domxref("Storage.removeItem()")}} {{readonlyInline}}
- When passed a key name, will remove that key from the storage.
- {{domxref("Storage.clear()")}} {{readonlyInline}}
- When invoked, will empty all keys out of the storage.
Examples
Here we access a Storage
object by calling localStorage
. We first test whether the local storage contains a data item using !localStorage.getItem('bgcolor')
. If it doesn't, we
if(!localStorage.getItem('bgcolor')) { populateStorage(); } else { setStyles(); } function populateStorage() { localStorage.setItem('bgcolor', document.getElementById('bgcolor').value); localStorage.setItem('font', document.getElementById('font').value); localStorage.setItem('image', document.getElementById('image').value); setStyles(); } function setStyles() { var currentColor = localStorage.getItem('bgcolor'); var currentFont = localStorage.getItem('font'); var currentImage = localStorage.getItem('image'); document.getElementById('bgcolor').value = currentColor; document.getElementById('font').value = currentFont; document.getElementById('image').value = currentImage; htmlElem.style.backgroundColor = '#' + currentColor; pElem.style.fontFamily = currentFont; imgElem.setAttribute('src', currentImage); }
Note: To see this running as a complete working example, see our Web Storage Demo.