较早的客户端存储数据的方式。
document.cookie = 'name_a=value_a'; document.cookie = 'name_b=value_b'; alert(document.cookie); // name_a=value_a;name_b=value_b
Cookie可以存储多个键值对,之间用分号';'进行分隔。每个键值对后可以跟一些特殊的属性:
;path=path
页面路径。默认是当前页;domain=example.com
;max-age=max-age-in-seconds
;expires=date-in-GMTString-format
;secure
如果出现,则cookie只通过https协议传输。if(window.localStorage){ localStorage['kname'] = 'kvalue'; } alert(localStorage['kname']);
localStorage
可以看作是globalStorage
的一个特例,即globalStorage[location.hostname]
。
localStorage在页面关闭后仍然存在。
和localStorage类似,只是生命周期和Session类似。页面刷新和崩溃后的重载也可以访问相应的sessionStorage。利用这个特性,可以自动保存用户输入的数据。
var field = document.getElementById("field"); if ( sessionStorage.autosave ) { // Restore the contents of the text field field.value = sessionStorage.autosave; } setInterval(function(){ // save the results into sessionStorage sessionStorage.autosave = field.value; }, 1000);
IE 8 以前的浏览器不支持 Storage,但可以通过 userData
来实现客户端存储。