|
localStorage |
sessionStorage |
生存周期 |
一直 |
在关闭页面后即被清空 |
大小限制 |
各个浏览器不一样。chrome限制为5m |
捕获存储异常
try {
localStorage.setItem(key, value);
} catch (oException) {
if (oException.name === 'QuotaExceededError') {
console.log('超出本地存储限额!');
// 清空后,再设置
localStorage.clear();
localStorage.setItem(key, value);
}
}
获取存储大小限制
(function() {
if (!window.localStorage) {
console.log('当前浏览器不支持localStorage!')
}
var test = '0123456789';
var add = function(num) {
num += num;
if (num.length == 10240) {
test = num;
return;
}
add(num);
}
add(test);
var sum = test;
var show = setInterval(function() {
sum += test;
try {
window.localStorage.removeItem('test');
window.localStorage.setItem('test', sum);
console.log(sum.length / 1024 + 'KB');
} catch (e) {
alert(sum.length / 1024 + 'KB超出最大限制');
clearInterval(show);
}
}, 0.1)
}
)()
获取当前存储的size
// 示例代码
function get_cache_size(t) {
t = t == undefined ? "l" : t;
var obj = "";
if (t === 'l') {
if (!window.localStorage) {
console.log('浏览器不支持localStorage');
} else {
obj = window.localStorage;
}
} else {
if (!window.sessionStorage) {
console.log('浏览器不支持sessionStorage');
} else {
obj = window.sessionStorage;
}
}
if (obj !== "") {
var size = 0;
for (item in obj) {
if (obj.hasOwnProperty(item)) {
size += obj.getItem(item).length;
}
}
console.log('当前已用存储:' + (size / 1024).toFixed(2) + 'KB');
}
}
get_cache_size('l'); //localStorage当前大小
get_cache_size('s'); //sessionStorage当前大小