JS获取浏览器localStorage存储上限
·
基本思路:不断的给字符串增加字符,调用 localStorage.setItem 进行存储,直至其无法存储为止(exceeded the quota:超出限额)。
注意事项:
- 给定的字符串不能过小,否则 js 代码执行非常慢,也不能过大,否则会造成较大的误差。
- 先成倍叠加获取一个使localStorage超限制的初始的字符串,再取其一半,减去一半的一半,判断是否超限制,如果没有,说明数据量不够,再加上一半的一半的一半,如果超限制,说明数据量过多,再减去一半的一半的一半,一次内推,直至一半的值为0。
- 不同的浏览器类型和版本,其对应的 localStorage 存储量可能不一致。
// 5MB: 5242880
function getLocalStorageSize () {
let str = '1'
while(1) { // 不断成倍叠加str直至超出localStorage的存储限制
str += str
try {
localStorage.removeItem('cache')
localStorage.setItem('cache', str)
} catch (err) {
console.log(err.name)
break;
}
}
console.log(str.length) // 8388608
let half = str.length / 2
let isAdd = 0
let len = str.length
let resStr = ''
while (half) {
half = Math.floor(half / 2)
if (isAdd) { // 加
len = len + half
} else { // 减
len = len - half
}
resStr = str.slice(0, len)
try {
localStorage.removeItem('cache')
localStorage.setItem('cache', resStr)
isAdd = 1
} catch (err) {
console.log('err', err)
// err DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'cache' exceeded the quota.
isAdd = 0
}
}
console.log(`chrome: ${resStr.length}B ${resStr.length / 1024 / 1024}MB`) // chrome: 5242875B ≈5MB
}
getLocalStorageSize()
更多推荐


所有评论(0)