Javascript 如何找到localStorage的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4391575/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find the size of localStorage
提问by derivation
I am currently developing a site that will make use of HTML5's localStorage. I've read all about the size limitations for different browsers. However, I haven't seen anything on how to find out the current size of a localStorage instance. This questionseems to indicate that JavaScript doesn't have a built in way of showing the size for a given variable. Does localStorage have a memory size property that I haven't seen? Is there an easy way to do this that I'm missing?
我目前正在开发一个将使用 HTML5 的 localStorage 的站点。我已阅读有关不同浏览器的大小限制的所有信息。但是,我还没有看到有关如何找出 localStorage 实例的当前大小的任何信息。这个问题似乎表明 JavaScript 没有内置的方式来显示给定变量的大小。localStorage 是否有我没见过的内存大小属性?有没有一种简单的方法可以做到这一点,我错过了?
My site is meant to allow users to enter information in an 'offline' mode, so being able to give them a warning when the storage is almost full is very important.
我的站点旨在允许用户以“离线”模式输入信息,因此能够在存储空间快满时向他们发出警告非常重要。
回答by Serge Seletskyy
Execute this snippet in JavaScript console (one line version):
在 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");
The same code in multiple lines for reading sake
多行相同的代码以供阅读
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");
or add this text in the field 'location' of a bookmark for convenient usage
或将此文本添加到书签的“位置”字段中以方便使用
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"));
P.S. Snippets are updated according to request in the comment. Now the calculation includes the length of the key itself. Each length is multiplied by 2 because the char in javascript stores as UTF-16 (occupies 2 bytes)
PS 片段根据评论中的要求更新。现在计算包括密钥本身的长度。每个长度乘以2,因为javascript中的char存储为UTF-16(占用2个字节)
P.P.S. Should work both in Chrome and Firefox.
PPS 应该可以在 Chrome 和 Firefox 中使用。
回答by tennisgent
Going off of what @Shourav said above, I wrote a small function that should accurately grab all your the localStorage
keys (for the current domain) and calculate the combined size so that you know exactly how much memory is taken up by your localStorage
object:
根据@Shourav 上面所说的,我编写了一个小函数,它应该准确地获取所有localStorage
键(对于当前域)并计算组合大小,以便您确切知道localStorage
对象占用了多少内存:
var localStorageSpace = function(){
var allStrings = '';
for(var key in window.localStorage){
if(window.localStorage.hasOwnProperty(key)){
allStrings += window.localStorage[key];
}
}
return allStrings ? 3 + ((allStrings.length*16)/(8*1024)) + ' KB' : 'Empty (0 KB)';
};
Mine returned: "30.896484375 KB"
我的回来了: "30.896484375 KB"
回答by Adam
IE has a remainingSpaceproperty of the Storage object. The other browsers have no equivilant at this time.
IE 具有Storage 对象的剩余空间属性。其他浏览器目前没有等效项。
I believe that the default amount of space is 5MB, although I have not tested it personally.
我相信默认的空间量是 5MB,虽然我没有亲自测试过。
回答by jas-
回答by Jakub Gadkowski
Hope this help someone.
希望这有助于某人。
Because Jas- example on jsfiddle does not work for me I came up with this solution. (thanks to Serge Seletskyy and Shourav for their bits I used in the code below)
因为 jsfiddle 上的 Jas 示例对我不起作用,所以我想出了这个解决方案。(感谢 Serge Seletskyy 和 Shourav 提供的我在下面的代码中使用的位)
Below is the function that can be used to test how much space is available for localStorage and (if any keys are already in lS) how much space is left.
下面的函数可用于测试 localStorage 有多少可用空间以及(如果 lS 中已经有任何键)剩余多少空间。
It is a little brute force but it works in almost every browser... apart from Firefox. Well in desktop FF it takes ages (4-5min) to complete, and on Android it just crashes.
这有点蛮力,但它几乎适用于所有浏览器……除了 Firefox。那么在桌面 FF 中它需要很长时间(4-5 分钟)才能完成,而在 Android 上它只是崩溃。
Underneath the function is a short summary of tests that I have done in different browsers on different platforms. Enjoy!
该函数下方是我在不同平台上的不同浏览器中进行的测试的简短摘要。享受!
function testLocalStorage() {
var timeStart = Date.now();
var timeEnd, countKey, countValue, amountLeft, itemLength;
var occupied = leftCount = 3; //Shurav's comment on initial overhead
//create localStorage entries until localStorage is totally filled and browser issues a warning.
var i = 0;
while (!error) {
try {
//length of the 'value' was picked to be a compromise between speed and accuracy,
// the longer the 'value' the quicker script and result less accurate. This one is around 2Kb
localStorage.setItem('testKey' + i, '11111111112222222222333333333344444444445555555555666661111111111222222222233333333334444444444555555555566666');
} catch (e) {
var error = e;
}
i++;
}
//if the warning was issued - localStorage is full.
if (error) {
//iterate through all keys and values to count their length
for (var i = 0; i < localStorage.length; i++) {
countKey = localStorage.key(i);
countValue = localStorage.getItem(localStorage.key(i));
itemLength = countKey.length + countValue.length;
//if the key is one of our 'test' keys count it separately
if (countKey.indexOf("testKey") !== -1) {
leftCount = leftCount + itemLength;
}
//count all keys and their values
occupied = occupied + itemLength;
}
;
//all keys + values lenght recalculated to Mb
occupied = (((occupied * 16) / (8 * 1024)) / 1024).toFixed(2);
//if there are any other keys then our 'testKeys' it will show how much localStorage is left
amountLeft = occupied - (((leftCount * 16) / (8 * 1024)) / 1024).toFixed(2);
//iterate through all localStorage keys and remove 'testKeys'
Object.keys(localStorage).forEach(function(key) {
if (key.indexOf("testKey") !== -1) {
localStorage.removeItem(key);
}
});
}
//calculate execution time
var timeEnd = Date.now();
var time = timeEnd - timeStart;
//create message
var message = 'Finished in: ' + time + 'ms \n total localStorage: ' + occupied + 'Mb \n localStorage left: ' + amountLeft + "Mb";
//put the message on the screen
document.getElementById('scene').innerText = message; //this works with Chrome,Safari, Opera, IE
//document.getElementById('scene').textContent = message; //Required for Firefox to show messages
}
And as promised above some test in different browsers:
正如上面所承诺的,在不同的浏览器中进行了一些测试:
GalaxyTab 10.1
银河标签 10.1
- Maxthon Pad 1.7 ~1130ms 5Mb
- Firefox 20.0(Beta 20.0) crashed both
- Chrome 25.0.1364.169 ~22250ms /5Mb
- Native (identifies as Safari 4.0/Webkit534.30) ~995ms /5Mb
- Maxthon Pad 1.7 ~1130ms 5Mb
- Firefox 20.0(Beta 20.0)同时崩溃
- 铬 25.0.1364.169 ~22250ms /5Mb
- 本机(标识为 Safari 4.0/Webkit534.30)~995ms /5Mb
iPhone 4s iOS 6.1.3
iPhone 4s iOS 6.1.3
- Safari ~ 520ms /5Mb
- As HomeApp ~525ms / 5Mb
- iCab ~ 710ms /5mb
- Safari ~ 520ms /5Mb
- 作为 HomeApp ~525ms / 5Mb
- iCab ~ 710ms /5mb
MacBook Pro OSX 1.8.3 (Core 2 Duo 2.66 8Gb memory)
MacBook Pro OSX 1.8.3(Core 2 Duo 2.66 8Gb 内存)
- Safari 6.0.3 ~105ms /5Mb
- Chrome 26.0.1410.43 ~3400ms /5Mb
- Firefox 20.0 300150ms(!) /10Mb (after complaining about script running to long)
- Safari 6.0.3 ~105ms /5Mb
- 铬 26.0.1410.43 ~3400ms /5Mb
- Firefox 20.0 300150ms(!) /10Mb(在抱怨脚本运行时间过长之后)
iPad 3 iOS 6.1.3
iPad 3 iOS 6.1.3
- Safari ~430ms /5Mb
- iCab ~595ms /5mb
- Safari ~430ms /5Mb
- iCab ~595ms /5mb
Windows 7 -64b (Core 2 Duo 2.93 6Gb memory)
Windows 7 -64b(Core 2 Duo 2.93 6Gb 内存)
- Safari 5.1.7 ~80ms /5Mb
- Chrome 26.0.1410.43 ~1220ms /5Mb
- Firefox 20.0 228500ms(!) /10Mb (after complaining about script running to long)
- IE9 ~17900ms /9.54Mb ( if any console.logs are in the code does not work until DevTools are opened)
- Opera 12.15 ~4212ms /3.55Mb (this is when 5Mb is selected, but Opera asks nicely if we want increase the amount of lS, unfortunately it crashes if test conducted a few times in a row)
- Safari 5.1.7 ~80ms /5Mb
- 铬 26.0.1410.43 ~1220ms /5Mb
- Firefox 20.0 228500ms(!) /10Mb(在抱怨脚本运行时间过长之后)
- IE9 ~17900ms /9.54Mb(如果代码中有任何 console.logs 在 DevTools 被打开之前不起作用)
- Opera 12.15 ~4212ms /3.55Mb(这是选择5Mb时,但Opera很好地询问我们是否要增加lS的数量,不幸的是如果连续进行几次测试它会崩溃)
Win 8 (Under Parallels 8)
Win 8(在 Parallels 8 下)
- IE10 ~7850ms /9.54Mb
- IE10 ~7850ms /9.54Mb
回答by P Roitto
You can get the current size of the local storage data using the Blob function.This may not work in old browsers, check the support for new Blob
and Object.values()
at caniuse.
您可以使用Blob 函数获取本地存储数据的当前大小。这可能不会在旧的浏览器工作,检查的支持new Blob
,并Object.values()
在caniuse。
Example:
例子:
return new Blob(Object.values(localStorage)).size;
Object.values() turns the localStorage object to an array. Blob turns the array into raw data.
Object.values() 将 localStorage 对象转换为数组。Blob 将数组转换为原始数据。
回答by Usman Faisal
You can calculate your localstorage by following methods:
您可以通过以下方法计算您的本地存储:
function sizeofAllStorage(){ // provide the size in bytes of the data currently stored
var size = 0;
for (i=0; i<=localStorage.length-1; i++)
{
key = localStorage.key(i);
size += lengthInUtf8Bytes(localStorage.getItem(key));
}
return size;
}
function lengthInUtf8Bytes(str) {
// Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
var m = encodeURIComponent(str).match(/%[89ABab]/g);
return str.length + (m ? m.length : 0);
}
console.log(sizeofAllStorage());
Finally size in bytes will be logged in browser.
最后以字节为单位的大小将记录在浏览器中。
回答by Arnaud Valensi
I would use the code of @tennisgen which get all and count the content, but I count the keys themselves:
我会使用@tennisgen 的代码来获取所有内容并计算内容,但我自己计算密钥:
var localStorageSpace = function(){
var allStrings = '';
for(var key in window.localStorage){
allStrings += key;
if(window.localStorage.hasOwnProperty(key)){
allStrings += window.localStorage[key];
}
}
return allStrings ? 3 + ((allStrings.length*16)/(8*1024)) + ' KB' : 'Empty (0 KB)';
};
回答by Mihir
In addition to @serge's answer which is most voted here, size of the keys need to be considered. Code below will add the size of the keys stored in localStorage
除了在这里投票最多的@serge 的答案之外,还需要考虑密钥的大小。下面的代码将添加存储在localStorage
var t = 0;
for (var x in localStorage) {
t += (x.length + localStorage[x].length) * 2;
}
console.log((t / 1024) + " KB");
回答by Jed
The way I went about this problem is to create functions for finding out the used space and remaining space in Local Storage and then a function that calls those functions to determine the max storage space.
我解决这个问题的方法是创建函数来找出本地存储中的已用空间和剩余空间,然后创建一个函数来调用这些函数来确定最大存储空间。
function getUsedSpaceOfLocalStorageInBytes() {
// Returns the total number of used space (in Bytes) of the Local Storage
var b = 0;
for (var key in window.localStorage) {
if (window.localStorage.hasOwnProperty(key)) {
b += key.length + localStorage.getItem(key).length;
}
}
return b;
}
function getUnusedSpaceOfLocalStorageInBytes() {
var maxByteSize = 10485760; // 10MB
var minByteSize = 0;
var tryByteSize = 0;
var testQuotaKey = 'testQuota';
var timeout = 20000;
var startTime = new Date().getTime();
var unusedSpace = 0;
do {
runtime = new Date().getTime() - startTime;
try {
tryByteSize = Math.floor((maxByteSize + minByteSize) / 2);
localStorage.setItem(testQuotaKey, new Array(tryByteSize).join('1'));
minByteSize = tryByteSize;
} catch (e) {
maxByteSize = tryByteSize - 1;
}
} while ((maxByteSize - minByteSize > 1) && runtime < timeout);
localStorage.removeItem(testQuotaKey);
if (runtime >= timeout) {
console.log("Unused space calculation may be off due to timeout.");
}
// Compensate for the byte size of the key that was used, then subtract 1 byte because the last value of the tryByteSize threw the exception
unusedSpace = tryByteSize + testQuotaKey.length - 1;
return unusedSpace;
}
function getLocalStorageQuotaInBytes() {
// Returns the total Bytes of Local Storage Space that the browser supports
var unused = getUnusedSpaceOfLocalStorageInBytes();
var used = getUsedSpaceOfLocalStorageInBytes();
var quota = unused + used;
return quota;
}