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 Window.sessionStorage
method; If you want to manipulate the local storage for a domain, you call Window.localStorage
.
Storage.length
Read only
Storage
object.Storage.key()
Storage.getItem()
Storage.setItem()
Storage.removeItem()
Storage.clear()
Here we access a Storage
object by calling localStorage
. We first test whether the local storage contains data items using !localStorage.getItem('bgcolor')
. If it does, we run a function called setStyles()
that grabs the data items using Storage.getItem()
and uses those values to update page styles. If it doesn't, we run another function, populateStorage()
, which uses Storage.setItem()
to set the item values, then runs setStyles()
.
if(!localStorage.getItem('bgcolor')) { populateStorage(); } setStyles(); function populateStorage() { localStorage.setItem('bgcolor', document.getElementById('bgcolor').value); localStorage.setItem('font', document.getElementById('font').value); localStorage.setItem('image', document.getElementById('image').value); } 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.
Specification | Status | Comment |
---|---|---|
Web Storage (Second edition) The definition of 'Storage' in that specification. | Recommendation |
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|---|
localStorage | 4 | (Yes) | 3.5 | 8 | 10.50 | 4 |
sessionStorage | 5 | ? | 2 | 8 | 10.50 | 4 |
Feature | Android | Edge | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | 2.1 | (Yes) | ? | 8 | 11 | 3.2[1] |
[1] Since iOS 5.1, Safari Mobile stores localStorage
data in the cache folder, which is subject to occasional clean up at the behest of the OS, typically if space is short.
All browsers have varying capacity levels for both localStorage and sessionStorage. Here is a detailed rundown of all the storage capacities for various browsers.
© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Storage