浏览器本地存储——从新浪微博得到的启示

偶然间发现如果输入一句话到微博文本框中,即使不提交,也会被持久化——你关掉浏览器再打开,还看到你写的东西,即使你退回再登录也是能够看到你写的东西;

image

但是在cookie里面并不能找到这句话,这就推翻了我对浏览器本地化只能存储到cookie中的认识;那么我想会不会ajax已经同步到了后台,由于存储的速度是立即的,使用ajax就会跟后台代码频繁交互,会拖累整个系统,所以我认为没有,而监控的结果也证明了我的想法;如在chrome里面输入一句话,打开IE登录同样的账号后就不会看到那句话;说明这句话还是持久化到本地了;

image

后来分析新浪的代码,得知,除了cookie,新的html5本地存储支持的更多,如localStorage。而新浪代码中用了三种方式:localStroage, IE的userData和cookie;而在chrome下显示locaStorage,证实了我的想法;

image

代码如下:

//storage
App.storage = (function() {
var a = window.localStorage;
if (window.ActiveXObject) {
store = document.documentElement;
STORE_NAME = “localstorage”;
try {
store.addBehavior(“#default#userdata”);
store.save(STORE_NAME)
} catch(b) {}
return {
set: function(g, h) {
try {
store.setAttribute(g, h);
store.save(STORE_NAME)
} catch(j) {}
},
get: function(g) {
try {
store.load(STORE_NAME);
return store.getAttribute(g)
} catch(h) {
return “”
}
},
del: function(g) {
try {
store.removeAttribute(g);
store.save(STORE_NAME)
} catch(h) {}
}
}
} else {
if (a) {
return {
get: function(g) {
return a.getItem(g) == null ? null: unescape(a.getItem(g))
},
set: function(g, h, j) {
a.setItem(g, escape(h))
},
del: function(g) {
a.removeItem(g)
},
clear: function() {
a.clear()
},
getAll: function() {
var g = a.length,
j = null,
m = [];
for (var h = 0; h < g; h++) {
j = a.key(h),
m.push(j + “=” + this.getKey(j))
}
return m.join(“; “)
}
}
} else {
return {
get: function(n) {
var j = document.cookie.split(“; “),
h = j.length,
g = [];
for (var m = 0; m < h; m++) {
g = j[m].split(“=”);
if (n === g[0]) {
return unescape(g[1])
}
}
return null
},
set: function(g, h, j) {
if (! (j && typeof j === date)) {
j = new Date(),
j.setDate(j.getDate() + 1)
}
document.cookie = g + “=” + escape(h) + “; expires=” + j.toGMTString()
},
del: function(g) {
document.cookie = g + “=”; expires=Fri, 31 Dec 1999 23:59:59 GMT;”
},
clear: function() {
var j = document.cookie.split(“; “),
h = j.length,
g = [];
for (var m = 0; m < h; m++) {
g = j[m].split(“=”);
this.deleteKey(g[0])
}
},
getAll: function() {
return unescape(document.cookie.toString())
}
}
}
}
}

发表评论

您的电子邮箱地址不会被公开。