localStorage sessionStorage cookie

浏览器端存储数据,cookie、sessionStorage、localStorage,这里重点说说localStorage的实际应用。

cookie、sessionStorage、localStorage 三者都是在浏览器端存储的数据,均同源,区分域。

cookie,默认各种浏览器都支持;容量较小、约4K;每次http请求时、浏览器都会把自身存的cookies发送到服务器,并且在浏览器和服务器之间来回传递,造成带宽浪费;cookie数据可以设置path、限制该cookie只属于该路径下。可以设置过期时间、不受浏览器关闭与否的影响。
JavaScript Cookies API

Web Storage

sessionStorage、localStorage 两者是 HTML5 Web Storage API 提供的;IE8+支持;sessionStoragelocalStorage 仅在本地保存,不会自动随http请求发到服务器;容量较大可达5M。
Web Storage 提供丰富接口,数据操作更简便。每个域(包括子域)有独立的存储空间,各个存储空间是完全独立的,因此不会造成数据混乱。
Web Storage API

sessionStorage

会话级别的存储:仅在当前浏览器窗口关闭前有效、sessionStorage 数据一直存在,刷新页面或进入同源的不同页面,数据始终存在。浏览器窗口关闭后,sessionStorage 数据立即被销毁。

localStorage

持久化的本地存储,数据一直存在,直到被主动删除。

基本的存储、读取

前些天在改造一个页面缩放比例提示插件的时候,就是新用到了 localStorage 来存储当前的缩放比例的。这里只是简单说明一下其基本存、取操作:

1
2
3
4
5
6
if(window.localStorage){
window.localStorage.setItem('ratio', 'value');
}
if(window.localStorage){
var ratio = window.localStorage.getItem('ratio');
}

当然,若非要兼容 ie6\ie7,那就得用 cookie 了:

1
2
3
4
5
6
7
//兼容ie6、ie7
if(window.localStorage){
window.localStorage.setItem('ratio', 'value');
}else{
Cookie.write('ratio', 'value');
}
var ratio = window.localStorage ? localStorage.getItem('ratio') : Cookie.read('ratio');

数组的存储、读取

localStorage 存的是字符串,若想要存数组、对象,我们需要在 setItem、getItem 的时候进行转换,主要是通过:
字符串转换成对象、数组:JSON.parse()
对象、数组转换成字符串:JSON.stringify()

近期在做一个颜色选择器控件的时候,需要新增一个最近使用的颜色功能,记录用户最近使用的不超过9种的颜色。用的也是 localStorage 来存储。这里分别定义了2个方法,读和写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//首先判断window.localStorage的支持性,
var canLocalStorageSet = window.localStorage && window.localStorage.setItem, // 检测localStorage是否可用
canLocalStorageGet = window.localStorage && window.localStorage.getItem,
getItem = function(){},
setItem = function(){};
//然后自定义getItem、setItem
if(canLocalStorageGet){
getItem = function(key){
return window.localStorage.getItem(key);
};
}
if(canLocalStorageSet){
setItem = function(key, value){
return window.localStorage.setItem(key, value);
};
}
//最近使用的颜色,从localStorage读出来
function getRecentColor(){
if(getItem('recentColor') == null){
return '';
}else{
var arrColor = JSON.parse(getItem('recentColor'));
return arrColor;
}
}
//最近使用的颜色,写进localStorage
function setRecentColor(colorHex){
if(getItem('recentColor') == null){
var arrColor = new Array(colorHex);
setItem('recentColor',JSON.stringify(arrColor));
}else{
var arrColor = JSON.parse(getItem('recentColor'));
//若有重复项,则不存
for(var i = 0;i < arrColor.length; i++){
if(arrColor[i] == colorHex){
return;
}
}
//等于9,先删除最后一项,再在前增加一项
if(arrColor.length == 9){
arrColor.pop();
arrColor.unshift(colorHex);
setItem('recentColor',JSON.stringify(arrColor));
}else{
arrColor.unshift(colorHex);
setItem('recentColor',JSON.stringify(arrColor));
}
}
}

当然,localStorage 还有其它的一些方法:
localStorage.removeItem("key"); 删除指定名的localStorage
localStorage.clear(); 清空所有的localStorage