-
Notifications
You must be signed in to change notification settings - Fork 118
/
Js代码计算LocalStorage容量.html
64 lines (53 loc) · 1.49 KB
/
Js代码计算LocalStorage容量.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body></body>
<script type="text/javascript">
let str = ''
let temp = ''
// 先做一个 10KB 的字符串
while (str.length !== 10240) {
str = str + '0123456789'
}
// 以最小 10kb 为单位 累加
const computedTotal = () => {
return new Promise((resolve, reject) => {
const timer = setInterval(() => {
try {
console.log(123456)
localStorage.setItem('temp', temp)
} catch (error) {
console.log('error', error)
//超出内存空间报错: error DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'temp' exceeded the quota.
console.log(1, temp.length)
clearInterval(timer)
// 统计完记得清空
localStorage.clear()
resolve()
}
temp += str
}, 0)
})
}
(async () => {
await computedTotal()
// console.log(`最大容量${total}KB`)
})()
// 当前已使用的 localStorage 空间
const computedUse = () => {
let cache = 0
for (let key in localStorage) {
if (localStorage.hasOwnProperty(key)) {
cache += localStorage.getItem(key).length
}
}
return (cache / 1024).toFixed(2)
}
// 剩余可用容量 = 总容量 - 已使用容量
</script>
</html>