cookie数据始终在同源的http请求中携带(即使不需要),即cookie在浏览器和服务器间来回传递。而sessionStorage和localStorage不会自动把数据发给服务器,仅在本地保存。
cookies
1.域+path+name 标识
2.name+value, 有服务器产生,发回client,保存在client (http 的set-cookies 字段)
3.每次http请求都会发送 Cookies中 “域+path”相同的所有cookie
4.大多数浏览器Cookie最大约为4K
5.浏览器可能还限制了用户计算机存储的cookie数量(如允许每个站点最多存储20个cookies,超过则删除旧的;有些浏览器还对所有站点的cookie总数作出限制,如300)
localStorage 1.域相关
2.永久保存在本地(client) 3.容量无限制 4.数据不会过期,除非由于security 原因或者用户请求删除
localStorage主要用到的
length:本地存储数据的个数
setItem(key,value):向key字段写入value数据或者通过.的方式(localStorage.name)
getItem(key):去key字段的数据或者通过.的方式(localStorage.name)
removeItem(key):移除key字段
clear():清空该域下的所有数据
key(i):获取第i个数据的key
;(function () { var Conts = '_keep_' var ls = localStorage var _storage = { get: function (key) { return ls.getItem(Conts + key) }, set: function (key, value) { ls.setItem(Conts + key, value) }, clear: function () { ls.clear() }, remove: function (key) { ls.removeItem(Conts + key) }, key: function (i) { return ls.key(i) }, len: function () { return ls.length } } var _cookie = { get : function (key) { var strcookie = document.cookie if (strcookie != "") { key = Conts + key var arrcookie = strcookie.split("; ") for ( var i = 0; i < arrcookie.length; i++) { var arr = arrcookie[i].split("=") if (arr[0] == key) { return arr[1] || "" } } } return "" }, set : function (key, value, expires, domain) { var ep = '' var date = new Date() var domain = typeof domain === 'boolean' ? this.getDomain() : (domain ? domain : '') key = Conts + key expires = (expires || 365) * 24 * 3600 date.setTime(date.getTime() + expires) ep = date.toGMTString() domain = domain ? (';domain=' + domain) : '' document.cookie = key + "=" + value + ";expires=" + ep + domain + ";path=/" }, clear : function () { var _this = this this.forEach(this.allKey(), function () { _this.remove(this.okey) }) }, remove: function (key) { this.set(key, '', -1) }, getDomain : function () { var domain = document.domain var index = domain.lastIndexOf('.') index = domain.substring(0, index).lastIndexOf('.') if (index == -1) { return domain } return domain.substring(index + 1) }, forEach: function (arr, fn) { for (var i = 0, len = arr.length; i < len; i++) { if (fn.call(arr[i], i) === false) { break; } } }, allKey: function () { var ck = document.cookie.split(';') var arr = [] var len = Conts.length; this.forEach(ck, function () { var _this = this.replace(/^\s*/,'') var str = _this.substr(0, len) if (str === Conts) { var temp = _this.split('=') var obj = {} obj[temp[0]] = temp[1] obj.key = temp[0] obj.okey = temp[0].substr(len) arr.push(obj) } }) return arr }, key: function (i) { var temp var allKey = this.allKey()[i] for(var i in allKey) { temp = allKey[i] } return temp }, len: function () { return this.allKey().length } } window.Keep = window.localStorage ? _storage : _cookie })();