小编典典

如何找到localStorage的大小

html

我目前正在开发一个使用HTML5的localStorage的站点。我已经阅读了有关不同浏览器大小限制的所有信息。但是,关于如何找出localStorage实例的当前大小,我还没有看到任何东西。这个问题似乎表明JavaScript没有内置的方式来显示给定变量的大小。localStorage是否具有我未见过的内存大小属性?有没有一种简单的方法可以做到这一点,而我却没有呢?

我的网站旨在允许用户以“离线”模式输入信息,因此能够在存储空间即将用尽时向他们发出警告非常重要。


阅读 589

收藏
2020-05-10

共1个答案

小编典典

在JavaScript控制台(单行版本)中执行以下代码段:

var _lsTotal=0,_xLen,_x;for(_x in localStorage){ if(!localStorage.hasOwnProperty(_x)){continue;} _xLen= ((localStorage[_x].length + _x.length)* 2);_lsTotal+=_xLen; console.log(_x.substr(0,50)+" = "+ (_xLen/1024).toFixed(2)+" KB")};console.log("Total = " + (_lsTotal / 1024).toFixed(2) + " KB");

多行阅读同一条代码

var _lsTotal = 0,
    _xLen, _x;
for (_x in localStorage) {
    if (!localStorage.hasOwnProperty(_x)) {
        continue;
    }
    _xLen = ((localStorage[_x].length + _x.length) * 2);
    _lsTotal += _xLen;
    console.log(_x.substr(0, 50) + " = " + (_xLen / 1024).toFixed(2) + " KB")
};
console.log("Total = " + (_lsTotal / 1024).toFixed(2) + " KB");

或将此文本添加到书签的“位置”字段中以方便使用

javascript: var x, xLen, log=[],total=0;for (x in localStorage){if(!localStorage.hasOwnProperty(x)){continue;} xLen =  ((localStorage[x].length * 2 + x.length * 2)/1024); log.push(x.substr(0,30) + " = " +  xLen.toFixed(2) + " KB"); total+= xLen}; if (total > 1024){log.unshift("Total = " + (total/1024).toFixed(2)+ " MB");}else{log.unshift("Total = " + total.toFixed(2)+ " KB");}; alert(log.join("\n"));

PS片段根据注释中的要求进行更新。现在,计算包括密钥本身的长度。每个长度都乘以2,因为javascript中的char存储为UTF-16(占用2个字节)

PPS应该可以在Chrome和Firefox中使用。

2020-05-10