本地存储是 HTML5 的一部分,用于方便地从页面存储本地数据。它包括 localStorage 和 sessionStorage 两种:前者保存的数据可以一直保存,除非清除浏览器缓存;而后者保存的数据在关闭浏览器后即失效。

本地存储 IE 8.0+,Firefox 3.5+,Chrome4.0+,Safari 4.0+ 和 Opera 10.5+ 都支持。使用方式也很简单:

if (window.localStorage){
    // set item
    localStorage.key1 = 'value1';
    localStorage['key2'] = 'value2';
    localStorage.setItem('key3', 'value3');

    // get item
    var a = localStorage.key1;
    var b = localStorage['key2'];
    var c = localStorage.getItem('key3');

    // delete item
    localStorage.removeItem('key');

    // clear all items
    localStorage.clear();   
}

本地存储只能储存字符串数据,因此在存取其它类型的数据需要进行转换。另外有些浏览器(例如 IE 9 和 Firefox 6)对本地打开的网页禁用了本地存储。

参考资料:
[1] Web Storage - W3C[2] DOM Storage - MDN[3] Web Storage Support Test[4] Local Storage - Dive Into HTML5[5] 八一下LocalStorage本地存储的卦 | Tencent AlloyTeam[6] JavaScript本地存储实践(html5的localStorage和ie的userData)[7] html5客户端本地存储之sessionStorage及storage事件[8] localStorage.setItem not persisting on refresh - stackoverflow[9] local storage in IE9 fails when the website is accessed directly from the file system
[A] Bug 507361 - localStorage doesn't work in file:/// documents