作为 Web Storage API 的接口,Storage 提供了访问特定域名下的会话存储(session storage)或本地存储(local storage)的功能,例如,可以添加、修改或删除存储的数据项。
如果你想要操作一个域名的会话存储(session storage),可以使用 Window.sessionStorage;如果想要操作一个域名的本地存储(local storage),可以使用 Window.localStorage。
属性
Storage.length只读- 返回一个整数,表示存储在
Storage对象中的数据项数量。
方法
Storage.key()- 该方法接受一个数值 n 作为参数,并返回存储中的第 n 个键名。
Storage.getItem()- 该方法接受一个键名作为参数,返回键名对应的值。
Storage.setItem()- 该方法接受一个键名和值作为参数,将会把键值对添加到存储中,如果键名存在,则更新其对应的值。
Storage.removeItem()- 该方法接受一个键名作为参数,并把该键名从存储中删除。
Storage.clear()- 调用该方法会清空存储中的所有键名。
示例
这里我们通过调用 localStorage 来访问一个 Storage 对象。首先,使用 !localStorage.getItem('bgcolor') 测试本地存储中是否包含该数据项。如果包含,则运行 setStyles() 函数,该函数使用 localStorage.getItem() 来获取数据项,并使用这些值更新页面样式。如果不包含,我们运行另一个函数 populateStorage(),该函数使用 localStorage.setItem() 设置数据项,然后运行 setStyles()。
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);
}
备注:要运行完整的例子,可查看 Web Storage Demo。
规范
| Specification | Status | Comment |
|---|---|---|
| Web Storage (Second edition) Storage |
Recommendation |
浏览器兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
|---|---|---|---|---|---|
| localStorage | 4 | 3.5 | 8 | 10.50 | 4 |
| sessionStorage | 5 | 2 | 8 | 10.50 | 4 |
| Feature | Android | Firefox Mobile (Gecko) | IE Phone | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | 2.1 | ? | 8 | 11 | iOS 3.2 |
各浏览器支持的 localStorage 和 sessionStorage 容量上限不同。测试页面 detailed rundown of all the storage capacities for various browsers.
Note: 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.