the storage of information of web app

来源:互联网 发布:广汽丰田面试经验知乎 编辑:程序博客网 时间:2024/06/05 23:46

a function needed by the project,storage the information of web app.






http://han.guokai.blog.163.com/blog/static/13671827120112694851799/

浏览器本地数据(sessionStorage、localStorage、cookie)与server端数据  

2011-03-06 23:48:21|  分类: 默认分类|举报|字号 订阅

  下载LOFTER我的照片书  |
sessionStorage 和 localStorage 是HTML5 Web Storage API 提供的,可以方便的在web请求之间保存数据。有了本地数据,就可以避免数据在浏览器和服务器间不必要地来回传递。

sessionStorage、localStorage、cookie都是在浏览器端存储的数据,其中sessionStorage的概念很特别,引入了一个“浏览器窗口”的概念。sessionStorage是在同源的同窗口(或tab)中,始终存在的数据。也就是说只要这个浏览器窗口没有关闭,即使刷新页面或进入同源另一页面,数据仍然存在。关闭窗口后,sessionStorage即被销毁。同时“独立”打开的不同窗口,即使是同一页面,sessionStorage对象也是不同的。

Web Storage带来的好处:
  1. 减少网络流量:一旦数据保存在本地后,就可以避免再向服务器请求数据,因此减少不必要的数据请求,减少数据在浏览器和服务器间不必要地来回传递。
  2. 快速显示数据:性能好,从本地读数据比通过网络从服务器获得数据快得多,本地数据可以即时获得。再加上网页本身也可以有缓存,因此整个页面和数据都在本地的话,可以立即显示。
  3. 临时存储:很多时候数据只需要在用户浏览一组页面期间使用,关闭窗口后数据就可以丢弃了,这种情况使用sessionStorage非常方便。


浏览器本地存储与服务器端存储之间的区别
其实数据既可以在浏览器本地存储,也可以在服务器端存储。

浏览器端可以保存一些数据,需要的时候直接从本地获取,sessionStorage、localStorage和cookie都由浏览器存储在本地的数据。

服务器端也可以保存所有用户的所有数据,但需要的时候浏览器要向服务器请求数据。
1.服务器端可以保存用户的持久数据,如数据库和云存储将用户的大量数据保存在服务器端。
2.服务器端也可以保存用户的临时会话数据。服务器端的session机制,如jsp的 session 对象,数据保存在服务器上。实现上,服务器和浏览器之间仅需传递session id即可,服务器根据session id找到对应用户的session对象。会话数据仅在一段时间内有效,这个时间就是server端设置的session有效期。

服务器端保存所有的用户的数据,所以服务器端的开销较大,而浏览器端保存则把不同用户需要的数据分布保存在用户各自的浏览器中。
浏览器端一般只用来存储小数据,而服务器可以存储大数据或小数据。
服务器存储数据安全一些,浏览器只适合存储一般数据。


sessionStorage 、localStorage 和 cookie 之间的区别
共同点:都是保存在浏览器端,且同源的。
区别:
  1. cookie数据始终在同源的http请求中携带(即使不需要),即cookie在浏览器和服务器间来回传递。而sessionStorage和localStorage不会自动把数据发给服务器,仅在本地保存。cookie数据还有路径(path)的概念,可以限制cookie只属于某个路径下。
  2. 存储大小限制也不同,cookie数据不能超过4k,同时因为每次http请求都会携带cookie,所以cookie只适合保存很小的数据,如会话标识。sessionStorage和localStorage 虽然也有存储大小的限制,但比cookie大得多,可以达到5M或更大。
  3. 数据有效期不同,sessionStorage:仅在当前浏览器窗口关闭前有效,自然也就不可能持久保持;localStorage:始终有效,窗口或浏览器关闭也一直保存,因此用作持久数据;cookie只在设置的cookie过期时间之前一直有效,即使窗口或浏览器关闭。
  4. 作用域不同,sessionStorage不在不同的浏览器窗口中共享,即使是同一个页面;localStorage 在所有同源窗口中都是共享的;cookie也是在所有同源窗口中都是共享的。
  5. Web Storage 支持事件通知机制,可以将数据更新的通知发送给监听者。
  6. Web Storage 的 api 接口使用更方便。

sessionStorage 和 localStorage 之间的区别
见上面的区别3、4

sessionStorage与页面 js 数据对象的区别
页面中一般的 js 对象或数据的生存期是仅在当前页面有效,因此刷新页面或转到另一页面这样的重新加载页面的情况,数据就不存在了。
而sessionStorage 只要同源的同窗口(或tab)中,刷新页面或进入同源的不同页面,数据始终存在。也就是说只要这个浏览器窗口没有关闭,加载新页面或重新加载,数据仍然存在。





http://www.cnblogs.com/xiaowei0705/archive/2011/04/19/2021372.html

HTML5 LocalStorage 本地存储

HTML5 LocalStorage 本地存储

说到本地存储,这玩意真是历尽千辛万苦才走到HTML5这一步,之前的历史大概如下图所示:

 

最早的Cookies自然是大家都知道,问题主要就是太小,大概也就4KB的样子,而且IE6只支持每个域名20cookies,太少了。优势就是大家都支持,而且支持得还蛮好。很早以前那些禁用cookies的用户也都慢慢的不存在了,就好像以前禁用javascript的用户不存在了一样。

 

userDataIE的东西,垃圾。现在用的最多的是Flash吧,空间是Cookie25倍,基本够用。再之后Google推出了Gears,虽然没有限制,但不爽的地方就是要装额外的插件(没具体研究过)。到了HTML5把这些都统一了,官方建议是每个网站5MB,非常大了,就存些字符串,足够了。比较诡异的是居然所有支持的浏览器目前都采用的5MB,尽管有一些浏览器可以让用户设置,但对于网页制作者来说,目前的形势就5MB来考虑是比较妥当的。



支持的情况如上图,IE8.0的时候就支持了,非常出人意料。不过需要注意的是,IEFirefox测试的时候需要把文件上传到服务器上(或者localhost),直接点开本地的HTML文件,是不行的。

 

首先自然是检测浏览器是否支持本地存储。在HTML5中,本地存储是一个window的属性,包括localStoragesessionStorage,从名字应该可以很清楚的辨认二者的区别,前者是一直存在本地的,后者只是伴随着session,窗口一旦关闭就没了。二者用法完全相同,这里以localStorage为例。

if(window.localStorage){
 alert('This browser supports localStorage');
}else{
 alert('This browser does NOT support localStorage');
}

 

存储数据的方法就是直接给window.localStorage添加一个属性,例如:window.localStorage.a 或者 window.localStorage["a"]。它的读取、写、删除操作方法很简单,是以键值对的方式存在的,如下:

localStorage.a = 3;//设置a"3"
localStorage["a"] = "sfsf";//设置a"sfsf",覆盖上面的值
localStorage.setItem("b","isaac");//设置b"isaac"
var a1 = localStorage["a"];//获取a的值
var a2 = localStorage.a;//获取a的值
var b = localStorage.getItem("b");//获取b的值
localStorage.removeItem("c");//清除c的值

 

这里最推荐使用的自然是getItem()setItem(),清除键值对使用removeItem()。如果希望一次性清除所有的键值对,可以使用clear()。另外,HTML5还提供了一个key()方法,可以在不知道有哪些键值的时候使用,如下:

var storage = window.localStorage;
function showStorage(){
 for(var i=0;i<storage.length;i++){
  //key(i)获得相应的键,再用getItem()方法获得对应的值
  document.write(storage.key(i)+ " : " + storage.getItem(storage.key(i)) + "<br>");
 }
}

 

写一个最简单的,利用本地存储的计数器:

var storage = window.localStorage;
if (!storage.getItem("pageLoadCount")) storage.setItem("pageLoadCount",0);
storage.pageLoadCount = parseInt(storage.getItem("pageLoadCount")) + 1;//必须格式转换
document.getElementByIdx_x("count").innerHTML = storage.pageLoadCount;
showStorage();

不断刷新就能看到数字在一点点上涨,如下图所示:

 

需要注意的是,HTML5本地存储只能存字符串,任何格式存储的时候都会被自动转为字符串,所以读取的时候,需要自己进行类型的转换。这也就是上一段代码中parseInt必须要使用的原因。

 

另外,在iPhone/iPad上有时设置setItem()时会出现诡异的QUOTA_EXCEEDED_ERR错误,这时一般在setItem之前,先removeItem()ok了。

 

HTML5的本地存储,还提供了一个storage事件,可以对键值对的改变进行监听,使用方法如下:

if(window.addEventListener){
 window.addEventListener("storage",handle_storage,false);
}else if(window.attachEvent){
 window.attachEvent("onstorage",handle_storage);
}
function handle_storage(e){
 if(!e){e=window.event;}
 //showStorage();
}

 

对于事件变量e,是一个StorageEvent对象,提供了一些实用的属性,可以很好的观察键值对的变化,如下表:

 Property

 Type

 Description

 key

 String

 The named key that was added, removed, or moddified

 oldValue

 Any

 The previous value(now overwritten), or null if a new item was added

 newValue

 Any

 The new value, or null if an item was added

 url/uri

 String

 The page that called the method that triggered this change

 

这里添加两个键值对ab,并增加一个按钮。给a设置固定的值,当点击按钮时,修改b的值:

<body>
<p>You have viewed this page <span id="count">0</span>  time(s).</p>
<p><input type="button" value="changeStorage" onClick="changeS()"/></p>
<script>
var storage = window.localStorage;
if (!storage.getItem("pageLoadCount")) storage.setItem("pageLoadCount",0);
storage.pageLoadCount = parseInt(storage.getItem("pageLoadCount")) + 1;//必须格式转换
document.getElementByIdx_x("count").innerHTML = storage.pageLoadCount;
showStorage();
if(window.addEventListener){
 window.addEventListener("storage",handle_storage,false);
}else if(window.attachEvent){
 window.attachEvent("onstorage",handle_storage);
}
function handle_storage(e){
 if(!e){e=window.event;}
 showObject(e);
}
function showObject(obj){
 //递归显示object
 if(!obj){return;}
 for(var i in obj){
  if(typeof(obj[i])!="object" || obj[i]==null){
   document.write(i + " : " + obj[i] + "<br/>");
  }else{
   document.write(i + " : object" + "<br/>");
  }
 }
}
storage.setItem("a",5);
function changeS(){
 //修改一个键值,测试storage事件
 if(!storage.getItem("b")){storage.setItem("b",0);}
 storage.setItem('b',parseInt(storage.getItem('b'))+1);
}
function showStorage(){
 //循环显示localStorage里的键值对
 for(var i=0;i<storage.length;i++){
  //key(i)获得相应的键,再用getItem()方法获得对应的值
  document.write(storage.key(i)+ " : " + storage.getItem(storage.key(i)) + "<br>");
 }
}
</script>
</body>

 

测试发现,目前浏览器对这个支持不太好,仅iPadFirefox支持,而且Firefox支持得乱糟糟,e对象根本没有那些属性。iPad支持非常好,用的是e.uri(不是e.url),台式机上的Safari不行,诡异。

 

目前浏览器都带有很好的开发者调试功能,下面分别是ChromeFirefox的调试工具查看LocalStorage



另外,目前javascript使用非常多的json格式,如果希望存储在本地,可以直接调用JSON.stringify()将其转为字符串。读取出来后调用JSON.parse()将字符串转为json格式,如下所示:

var details = {author:"isaac","description":"fresheggs","rating":100};
storage.setItem("details",JSON.stringify(details));
details = JSON.parse(storage.getItem("details"));

 

JSON对象在支持localStorage的浏览器上基本都支持,需要注意的是IE8,它支持JSON,但如果添加了如下的兼容模式代码,切到IE7模式就不行了(此时依然支持localStorage,虽然显示window.localStorage[object],而不是之前的[object Storage],但测试发现getItem()setItem()等均能使用)。

<meta content="IE=7" http-equiv="X-UA-Compatible"/>

 

经验在于积累----小伟
好文要顶 关注我 收藏该文  
xiaowei0705
关注 - 1
粉丝 - 107
+加关注
66
0
« 上一篇:js调用.net后台事件,和后台调用前台等方法总结
» 下一篇:什么样的情况会导致网页不断的崩溃
posted on 2011-04-19 17:53 xiaowei0705 阅读(362636) 评论(42) 编辑 收藏

评论:
#1楼 2011-04-19 22:54 | 0x0qwe  
博主,图全瓜了。。。。
支持(0)反对(0)
  
#2楼[楼主2011-04-20 09:44 | xiaowei0705  
@ 0x0qwe
啥意思!!!
支持(0)反对(0)
  
#3楼[楼主2011-04-27 10:13 | xiaowei0705  
@ 0x0qwe
呵呵!!!图片出问题了!!
支持(0)反对(0)
  
#4楼 2011-11-30 17:54 | 呦菜  
刚用这个东西呢,呵呵~~很有帮助!!!
支持(0)反对(0)
  
#5楼 2012-07-12 10:10 | blog.gaoshou.org  
写的几个例子都不要用。。。!真心不好用
支持(0)反对(0)
  
#6楼 2012-08-19 10:24 | 石斧砍柴好慢  
最近也用过本地存储。再读楼主的文章,受益匪浅!
支持(0)反对(0)
  
#7楼 2012-08-29 21:54 | 深海沉  
不错
支持(0)反对(0)
  
#8楼 2012-11-20 11:17 | rainyjune  
注意 storage 事件是在同域下的其他网页中触发的,而不是当前的页面。如下引用自 《JavaScript:The Definitive Guide》(6th Edition):

[quote]Whenever the data stored in localStorage or sessionStorage changes, the browser
triggers a storage event on any other Window objects to which that data is visible (but
not on the window that made the change). If a browser has two tabs open to pages with
the same origin, and one of those pages stores a value in localStorage, the other tab
will receive a storage event.[/quote]
支持(2)反对(0)
  
#9楼 2013-01-23 00:29 | 艹蛋的青春じ 让我蛋疼ミ  
请问htm5 的 LocalStorage 本地存储, 在电脑什么位置,如果我里面记录的是,帐号密码,存不存在风险
支持(0)反对(0)
  
#10楼 2013-04-22 23:46 | 诸葛囧明  
@ 艹蛋的青春じ 让我蛋疼ミ
清除用浏览器的清除本地数据即可呀
支持(0)反对(0)
  
#11楼 2013-07-10 16:06 | 九月枫林  
受用,谢谢
支持(0)反对(0)
  
#12楼 2013-07-13 15:21 | 暮光青年  
好文章,收藏了。。。。
支持(0)反对(0)
  
#13楼 2013-07-23 20:53 | PowerAuras  
good 感谢
支持(0)反对(0)
  
#14楼 2013-11-01 16:02 | 12饕餮21  
@ 艹蛋的青春じ 让我蛋疼ミ
你把它当容量更大的cookie就好
支持(0)反对(0)
  
#15楼 2013-11-18 10:41 | yuqi@dl  
刚学这个东东,很有帮助。谢谢!
支持(0)反对(0)
  
#16楼 2013-12-30 14:50 | 、Dark  
有过期时间设置吗?
支持(0)反对(0)
  
#17楼 2014-05-20 14:33 | snowinmay  
不错~~~~
支持(0)反对(0)
  
#18楼 2014-08-28 07:13 | 移花香  
@ 诸葛囧明
@艹蛋的青春じ 让我蛋疼ミ
关于“请问htm5 的 LocalStorage 本地存储, 在电脑什么位置,如果我里面记录的是,帐号密码,存不存在风险”

如果网页自动记录密码的话使用的cookie吗?如果是,记录前应该要加密(不知有没加密?如何加密?)没有加密的话,每次http请求的时候都会吧cookie发送到服务器,而再次过程中有无风险?望指教。
支持(0)反对(0)
  
#19楼 2014-11-25 11:05 | feibinyang  
好文 赞
支持(0)反对(0)
  
#20楼 2015-01-04 16:43 | 狼骑_叛逃者开发组  
很久以前就看到这个了,第一次能读懂。
很有用,感谢(我一直都用Session来保存全局变量,看完之后,醉了)
支持(1)反对(0)
  
#21楼 2015-01-04 16:44 | 狼骑_叛逃者开发组  
@ 移花香
cookie风险比session更大,无论是cookie还是session,必要的都要自己写加密的
支持(0)反对(0)
  
#22楼 2015-01-05 20:49 | Macy Hao  
受用
支持(0)反对(0)
  
#23楼 2015-01-14 14:36 | 金昔过  
好东西,最近也在研究呢,收藏了
支持(0)反对(0)
  
#24楼 2015-01-28 17:47 | bugong  
mark
支持(0)反对(0)
  
#25楼 2015-04-07 15:40 | Joans  
good,ths
支持(0)反对(0)
  
#26楼 2015-12-01 10:10 | 高尔础础  
最近项目中几个使用localStorage的,清除单个key值都是参考的
支持(0)反对(0)
  
#27楼 2016-03-14 19:27 | Naylor  
楼主,你讲解的真好!我一看就懂了!
支持(0)反对(0)
  
#28楼 2016-03-14 19:27 | Naylor  
<img src="http://images2015.cnblogs.com/blog/718864/201603/718864-20160314192754912-847542641.jpg" alt="" border="0" "="" style="border: 0px; max-width: 400px;">
支持(2)反对(0)
  
#29楼 2016-03-17 17:10 | 前端开发搞笑师  
@ Naylor
引用500) this.width=500;" width="500">

为了楼主的好文章和这个好妹子,评论一个!赞!!!
支持(0)反对(0)
  
#30楼 2016-03-17 17:14 | 咧嘴玩手机的猫  
不错不错
支持(0)反对(0)
  
#31楼 2016-03-17 17:21 | 顾晓北  
https://www.google.com.hk/search?tbs=sbi:AMhZZiuLwIkPsDDOLjavY-zKNmVxyU0lW4-8n4xUXAgiWnXPP2AN7DqjOdNeFu8H8B-M_1OhfsRGKmdNTjBQrrOBvf3Q_1JTCxRJhlTYAL8HEKbwt70FPhU3Q8GUO28pwbLCZ2wtTL5hAKNSSEl-q6JAvzVLB0nuPBhGWmJy90Xgpo951acE1ZBf38xOr7sGpu6SWMBQPqak8Wy9RZ0XAF584ur0zMxu7hQD14MAByaf8twKqTcSsDp2cvkr4Tq1KmnZkK9CDV0el1Tcg6BtjWQDXaz62_1MrsWk9upPTZoJFR4J4Vw3WCNs1f8KPmAd0kkppCS3TC3d8dRxHYK4K8mxigM5ur9vQ3nOW6z6J8Qg-N9EKbq1DyfZ9y7zFtqpXKgRG9-ff8-pcL5P4yoJulLD_1rdRUlD5GVHEbq5GaKnLxM9AMXGLwn-j0Rn5xdasbdxs6eYoZ_1PZATSs73rTlHD6-EjalIuvjJVF9RCMjbxB4GfLt6vvUCdJW2kb22u-gxwL8p-Detqj94prfnUHF-yIjICrXiOXEHn-T_1gmRSWTviVqZ4QnbhOiVVPHFy9gjnJS9mUhnz-2HNszJLNgRtg3Sl40yXk7UmjMIPK6ULPWzZYTjtPhUyy61ncnZmTCtP8OAc9_1ETkDmc0EqMHUb0HgFwlwJX_1-NAFaQSWKVtgArA0FEoJyKSkJN7C4YwRwzsTL8mKN1sIt88qIb1X5BFXwyZ-vmZ8DP-pY_1P_18ZwYw6HfGtttCX8ej7mUDJT8ZK4M03kjCJgNUxyqygmWLXnMqfIwYIWbPYTqlaHw42jKw1Iq_1URCb-JmHlLacTLVSa7_1GS55uf-29g22XMhjHbxQPvj9Dx6drEvr3luY5Lr7T89v-Na6TAHzsH9xIvK8r6bCjSr2WcukpeXQhCIiNOpN5WpSjxro5ta2Be9ik-m-AGmAxUnvBZtKjQZS55m8cMi180q_1hxfvxMpb6ZA5FXK-Oh7xhHtTSJa2drR1tSQoRPWd5H5kDjKtCpTOMqCZR-eAQEwLFxdjCBTZlml8OjqKvYLSI368wH9HdlcwRj381lZJQW8ieWeEnPUkh51EH8XfkX0ODphCpy9fMG3kywZXHstkXYsHKxlZkWcta-tzSdFyP816uugVaGnur7PhZ42S0ORF09kx31rwdegwAN7bNI5c-oVCa-q9hPSjMdCPWwH5QN1kzZ08rO74a_1gQBnI2cJq-muhvqiEF25_1ph0_1fsFay6y4LMbXAJAteFllWzVhnkvUKhD4J-nfnoNHM5IDZ9IqQil0SUhkBswdv5jNDMOqIhVNfDjqeVfEV_1ekU3HcDFknX1gN84CI2xZZbTjElw9EUWKTUHJw8DsC02VEI4l7KCx0c4SjiQ0A_1Wd9PbZnOmAUxQ2Sx7tj8_19CPBNShwadAfCAZbS-213igPqNU_1lVHPrfItWBhqZ9H1JIxc06n62_1Zu8_1SItGNEJ4UqGS5kGGNKkbNf5od-_1TPrLI5TnQ_1gFToajCA6KX8Q1R1dwru0qmm9_1As-qwdYrEFR6knpfsliK439nW8oERnds0YE3dYS27h4Obcaw9Nd9htE22IdKgWv2pZcsiKc_1f1At9Lub0ylJx7GJ5ceM1aUK3PLZtkqlTsT_1VoNg
支持(0)反对(0)
  
#32楼 2016-04-01 09:00 | 我就不吃芹菜  
学习了
支持(0)反对(0)
  
#33楼 2016-04-16 18:38 | 玉龙岛主  
写的很好,受教了
支持(0)反对(0)
  
#34楼 2016-04-19 15:30 | 林七七  
@ blog.gaoshou.org
啊 还可以啊 挺详细的
支持(0)反对(0)
  
#35楼 2016-06-27 17:45 | LosPollos_Gus  
妹子图哪里冒出来的,(⊙o⊙)…
支持(0)反对(0)
  
#36楼 2016-06-30 11:32 | xiyouMc  
写的很好 。学到了
支持(0)反对(0)
  
#37楼 2016-07-24 11:52 | 平和的心  
@ Naylor
看文章还有这个福利,不错,妹子长得很卡哇伊
支持(0)反对(0)
  
#38楼 2016-08-06 20:05 | 牛腩  
支持支持
支持(0)反对(0)
  
#39楼 2016-09-02 17:10 | 小○○  
楼主,根据key可以删除,那么下面这种数据格式呢?需要删除msgid为15484的这条记录 {
"chatlog": {

"friend01006": [
{

"cmd": "1", 
"msgid": "15483"
}, 
{

"cmd": "1", 
"msgid": "15484"
}




}
}
支持(0)反对(0)
  
#40楼 2016-09-12 10:00 | 曹杰博  
不错~~~ ~!! 解决了 微信 里面记住密码的功能~~~ 顶顶~~~
支持(1)反对(0)
  
#41楼 2016-11-10 14:09 | 萧紫紫  
good
支持(0)反对(0)
  
#42楼 2016-12-07 23:50 | JackZhouMine  
请问你的chrome控制面板是咋个弄的?这么好看。




http://jerryzou.com/posts/cookie-and-web-storage/

详说 Cookie, LocalStorage 与 SessionStorage

May 2, 2015 浏览量:23,004 | Cookie LocalStorage HTML5

最近在找暑期实习,其中百度、网易游戏、阿里的面试都问到一些关于HTML5的东西,问题大多是这样开头的:“你用过什么HTML5的技术呀?” 而后,每次都能扯到 Cookie 和 localStorage 有啥差别。这篇文章就旨在详细地阐述这部分内容,而具体 Web Storage API 的使用可以参考MDN的文档,就不在这篇文章中赘述了。

基本概念

Cookie 是小甜饼的意思。顾名思义,cookie 确实非常小,它的大小限制为4KB左右,是网景公司的前雇员 Lou Montulli 在1993年3月的发明。它的主要用途有保存登录信息,比如你登录某个网站市场可以看到“记住密码”,这通常就是通过在 Cookie 中存入一段辨别用户身份的数据来实现的。

localStorage

localStorage 是 HTML5 标准中新加入的技术,它并不是什么划时代的新东西。早在 IE 6 时代,就有一个叫 userData 的东西用于本地存储,而当时考虑到浏览器兼容性,更通用的方案是使用 Flash。而如今,localStorage 被大多数浏览器所支持,如果你的网站需要支持 IE6+,那以 userData 作为你的 polyfill 的方案是种不错的选择。

特性ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)localStorage43.5810.504sessionStorage52810.504

sessionStorage

sessionStorage 与 localStorage 的接口类似,但保存数据的生命周期与 localStorage 不同。做过后端开发的同学应该知道 Session 这个词的意思,直译过来是“会话”。而 sessionStorage 是一个前端的概念,它只是可以将一部分数据在当前会话中保存下来,刷新页面数据依旧存在。但当页面关闭后,sessionStorage 中的数据就会被清空。

三者的异同

特性CookielocalStoragesessionStorage数据的生命期一般由服务器生成,可设置失效时间。如果在浏览器端生成Cookie,默认是关闭浏览器后失效除非被清除,否则永久保存仅在当前会话下有效,关闭页面或浏览器后被清除存放数据大小4K左右一般为5MB与服务器端通信每次都会携带在HTTP头中,如果使用cookie保存过多数据会带来性能问题仅在客户端(即浏览器)中保存,不参与和服务器的通信易用性需要程序员自己封装,源生的Cookie接口不友好源生接口可以接受,亦可再次封装来对Object和Array有更好的支持

应用场景

有了对上面这些差别的直观理解,我们就可以讨论三者的应用场景了。

因为考虑到每个 HTTP 请求都会带着 Cookie 的信息,所以 Cookie 当然是能精简就精简啦,比较常用的一个应用场景就是判断用户是否登录。针对登录过的用户,服务器端会在他登录时往 Cookie 中插入一段加密过的唯一辨识单一用户的辨识码,下次只要读取这个值就可以判断当前用户是否登录啦。曾经还使用 Cookie 来保存用户在电商网站的购物车信息,如今有了 localStorage,似乎在这个方面也可以给 Cookie 放个假了~

而另一方面 localStorage 接替了 Cookie 管理购物车的工作,同时也能胜任其他一些工作。比如HTML5游戏通常会产生一些本地数据,localStorage 也是非常适用的。如果遇到一些内容特别多的表单,为了优化用户体验,我们可能要把表单页面拆分成多个子页面,然后按步骤引导用户填写。这时候 sessionStorage 的作用就发挥出来了。

安全性的考虑

需要注意的是,不是什么数据都适合放在 Cookie、localStorage 和 sessionStorage 中的。使用它们的时候,需要时刻注意是否有代码存在 XSS 注入的风险。因为只要打开控制台,你就随意修改它们的值,也就是说如果你的网站中有 XSS 的风险,它们就能对你的 localStorage 肆意妄为。所以千万不要用它们存储你系统中的敏感数据。

参考资料

  • what is the difference between localStorage, sessionStorage, session and cookie?
  • HTML5 localStorage security
  • 维基百科 - Cookie
  • Web Storage API
  • 浏览器本地数据(sessionStorage、localStorage、cookie)与server端数据
  • HTMl5的sessionStorage和localStorage
  • HTML5 LocalStorage 本地存储





Using the Web Storage API

In This Article

The Web Storage API provides mechanisms by which browsers can securely store key/value pairs, in a much more intuitive fashion than using cookies. This article provides a walkthrough of how to make use of this simple technology.

Basic conceptsEdit

Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads.  The keys and the values are always strings (note that integer keys will be automatically converted to strings, just like what objects do). You can access these values like an object, or with the Storage.getItem() and Storage.setItem() methods.  These three lines all set the colorSetting entry in the same way:

localStorage.colorSetting = '#a4509b';localStorage['colorSetting'] = '#a4509b';localStorage.setItem('colorSetting', '#a4509b');

Note: It's recommended to use the Web Storage API (setItemgetItemremoveItemkeylength) to prevent the pitfalls associated with using plain objects as key-value stores.

The two mechanisms within Web Storage are as follows:

  • sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).
  • localStorage does the same thing, but persists even when the browser is closed and reopened.

These mechanisms are available via the Window.sessionStorage and Window.localStorage properties (to be more precise, in supporting browsers the Window object implements the WindowLocalStorage and WindowSessionStorageobjects, which the localStorage and sessionStorage properties hang off) — invoking one of these will create an instance of the Storage object, through which data items can be set, retrieved, and removed. A different Storage object is used for the sessionStorage and localStorage for each origin — they function and are controlled separately.

So, for example, initially calling localStorage on a document will return a Storage object; calling sessionStorage on a document will return a different Storage object. Both of these can be manipulated in the same way, but separately.

Feature-detecting localStorageEdit

To be able to use localStorage, we should first verify that it is supported and available in the current browsing session.

Testing for availability

Browsers that support localStorage will have a property on the window object named localStorage. However, for various reasons, just asserting that property exists may throw exceptions. If it does exist, that is still no guarantee that localStorage is actually available, as various browsers offer settings that disable localStorage. So a browser may supportlocalStorage, but not make it available to the scripts on the page. One example of that is Safari, which in Private Browsing mode gives us an empty localStorage object with a quota of zero, effectively making it unusable. However, we might still get a legitimate QuotaExceededError, which only means that we've used up all available storage space, but storage is actually available. Our feature detect should take these scenarios into account. 

Here is a function that detects whether localStorage is both supported and available:

function storageAvailable(type) {    try {        var storage = window[type],            x = '__storage_test__';        storage.setItem(x, x);        storage.removeItem(x);        return true;    }    catch(e) {        return e instanceof DOMException && (            // everything except Firefox            e.code === 22 ||            // Firefox            e.code === 1014 ||            // test name field too, because code might not be present            // everything except Firefox            e.name === 'QuotaExceededError' ||            // Firefox            e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&            // acknowledge QuotaExceededError only if there's something already stored            storage.length !== 0;    }}

And here is how you would use it:

if (storageAvailable('localStorage')) {  // Yippee! We can use localStorage awesomeness}else {  // Too bad, no localStorage for us}

You can test for sessionStorage instead by calling storageAvailable('sessionStorage')

See here for a brief history of feature-detecting localStorage.

A simple exampleEdit

To illustrate some typical web storage usage, we have created a simple example, imaginatively called Web Storage Demo. The landing page provides controls that can be used to customize the color, font, and decorative image:

When you choose different options, the page is instantly updated; in addition, your choices are stored in localStorage,  so that when you leave the page and load it again later on, your choices are remembered.

We have also provided an event output page — if you load this page in another tab, then make changes to your choices in the landing page, you'll see the updated storage information outputted as a StorageEvent is fired.

Note: As well as viewing the example pages live using the above links, you can also check out the source code.

Testing whether your storage has been populatedEdit

To start with on main.js, we will test whether the storage object has already been populated (i.e., the page was previously accessed):

if(!localStorage.getItem('bgcolor')) {  populateStorage();} else {  setStyles();}

The Storage.getItem() method is used to get a data item from storage; in this case we are testing to see whether the bgcolor item exists; if not, we run populateStorage() to add the existing customization values to the storage. If there are already values there, we run setStyles() to update the page styling with the stored values.

Note: You could also use Storage.length to test whether the storage object is empty or not.

Getting values from storageEdit

As noted above, values can be retrieved from storage using Storage.getItem(). This takes the key of the data item as an argument, and returns the data value. For example:

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);}

Here, the first three lines grab the values from local storage. Next, we set the values displayed in the form elements to those values, so that they keep in sync when you reload the page. Finally, we update the styles/decorative image on the page, so your customization options come up again on reload.

Setting values in storageEdit

Storage.setItem() is used both to create new data items, and (if the data item already exists) update existing values. This takes two arguments — the key of the data item to create/modify, and the value to store in it.

function populateStorage() {  localStorage.setItem('bgcolor', document.getElementById('bgcolor').value);  localStorage.setItem('font', document.getElementById('font').value);  localStorage.setItem('image', document.getElementById('image').value);  setStyles();}

The populateStorage() function sets three items in local storage — the background color, font, and image path. It then runs the setStyles() function to update the page styles, etc.

We've also included an onchange handler on each form element, so that the data and styling is updated whenever a form value is changed:

bgcolorForm.onchange = populateStorage;fontForm.onchange = populateStorage;imageForm.onchange = populateStorage;

Responding to storage changes with the StorageEventEdit

The StorageEvent is fired whenever a change is made to the Storage object (note that this event is not fired for sessionStorage changes). This won't work on the same page that is making the changes — it is really a way for other pages on the domain using the storage to sync any changes that are made. Pages on other domains can't access the same storage objects.

On the events page (see events.js) the only JavaScript is as follows:

window.addEventListener('storage', function(e) {    document.querySelector('.my-key').textContent = e.key;  document.querySelector('.my-old').textContent = e.oldValue;  document.querySelector('.my-new').textContent = e.newValue;  document.querySelector('.my-url').textContent = e.url;  document.querySelector('.my-storage').textContent = e.storageArea;});

Here we add an event listener to the window object that fires when the Storage object associated with the current origin is changed. As you can see above, the event object associated with this event has a number of properties containing useful information — the key of the data that changed, the old value before the change, the new value after that change, the URL of the document that changed the storage, and the storage object itself.

Deleting data recordsEdit

Web Storage also provides a couple of simple methods to remove data. We don't use these in our demo, but they are very simple to add to your project:

  • Storage.removeItem() takes a single argument — the key of the data item you want to remove — and removes it from the storage object for that domain.
  • Storage.clear() takes no arguments, and simply empties the entire storage object for that domain.

SpecificationsEdit

SpecificationStatusCommentHTML Living StandardLiving Standard 

Browser compatibilityEdit

  • Desktop 
  • Mobile
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)localStorage43.5810.504sessionStorage52810.504

All browsers have varying capacity levels for both localStorage and sessionStorage. Here is a 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.

See alsoEdit

  • Web Storage API landing page


原创粉丝点击