如何查看localStorage的大小

发布于 2024-10-06 16:25:11 字数 332 浏览 5 评论 0原文

我目前正在开发一个将利用 HTML5 的 localStorage 的网站。我已阅读有关不同浏览器的大小限制的所有内容。但是,我还没有看到任何有关如何查找 localStorage 实例的当前大小的内容。 这个问题似乎表明JavaScript没有内置的方式来显示给定的大小多变的。 localStorage 是否有我没见过的内存大小属性?有没有一种简单的方法可以做到我所缺少的?

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

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 question seems 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?

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

够钟 2024-10-13 16:25:12

我会使用 @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)';
    };

I would use the code of @tennisgen which get all and count the content, but I count the keys themselves:

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)';
    };
羁客 2024-10-13 16:25:12

除了这里投票最多的@serge 的答案之外,还需要考虑密钥的大小。下面的代码将添加存储在 localStorage 中的密钥的大小

var t = 0; 
for (var x in localStorage) { 
    t += (x.length + localStorage[x].length) * 2; 
} 
console.log((t / 1024) + " KB");

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

var t = 0; 
for (var x in localStorage) { 
    t += (x.length + localStorage[x].length) * 2; 
} 
console.log((t / 1024) + " KB");
心碎无痕… 2024-10-13 16:25:12

按照规范,字符串的每个字符都是 16 位。

但是用chrome检查(设置>内容设置>Cookies和站点数据)显示启动localStorage需要3kB(开销大小)

并且存储的数据大小遵循这个关系(精确到1kB)
3 + ((localStorage.x.length*16)/(8*1024)) kB

其中 localStorage.x 是您的存储字符串。

As the spec goes, each character of a string is 16 bit.

But inspecting with chrome (Settings>Content Settings>Cookies & Site data) shows us that initiating localStorage takes 3kB (overhead size)

And stored data size follows this relation (accurate to 1kB)
3 + ((localStorage.x.length*16)/(8*1024)) kB

where localStorage.x is your storage string.

徒留西风 2024-10-13 16:25:12

是的,这个问题10年前就有人问过。但对于那些感兴趣的人(比如我自己,因为我正在构建一个离线文本编辑器,用本地存储保存数据)并且不擅长编程,您可以使用像这样简单的东西:

var warning = 1;
var limit = 2000000; //2 million characters, not really taking in account to bytes but for tested number of characters stored
setInterval(function() {
    localStorage["text"] = document.getElementById("editor").innerHTML; //gets text and saves it in local storage under "text"
    if(localStorage["text"].length > limit && warning == 1){
            alert("Local Storage capacity has been filled"); 
            warning = 2; //prevent a stream of alerts
    }
}, 1000);
//setInterval function saves and checks local storage

获取存储量填充的最佳方法是查看站点设置(例如,如果您将图像存储在本地存储中)。至少在chrome中,您可以看到使用的字节数(即:1222字节)。然而,上面已经提到了用js查看本地存储已满的最佳方法,所以使用它们。

Yes, this question was asked like 10 years ago. But for those interested (like myself, as I am building an offline text editor that saves data with local storage) and suck at programming, you could use something simple like this:

var warning = 1;
var limit = 2000000; //2 million characters, not really taking in account to bytes but for tested number of characters stored
setInterval(function() {
    localStorage["text"] = document.getElementById("editor").innerHTML; //gets text and saves it in local storage under "text"
    if(localStorage["text"].length > limit && warning == 1){
            alert("Local Storage capacity has been filled"); 
            warning = 2; //prevent a stream of alerts
    }
}, 1000);
//setInterval function saves and checks local storage

The best way to get the amount of storage filled is to view the site settings (say, if you stored an image in local storage). At least in chrome, you can see the amount of bytes used (ie: 1222 bytes). However, the best ways to see filled local storage with js have already been mentioned above, so use them.

黑色毁心梦 2024-10-13 16:25:12

我只是在页面加载后或在任何输入焦点处使用带有一些测试内容的 try/catch,例如:

function canSetItem(){
    const KEY = "check_available_space"
    try {
        localStorage.setItem(KEY, KEY);
    } catch(e) {
        console.error(e);
        return false;
    }
    localStorage.removeItem(KEY);
    return true;
}

I would just use a try/catch with some test content after the page loads or at any input focus, like:

function canSetItem(){
    const KEY = "check_available_space"
    try {
        localStorage.setItem(KEY, KEY);
    } catch(e) {
        console.error(e);
        return false;
    }
    localStorage.removeItem(KEY);
    return true;
}
甜味超标? 2024-10-13 16:25:12

//键和值都占用内存,因此更新了代码。

var jsonarr=[];
var jobj=null;
for(x in sessionStorage) // Iterate through each session key
{
    jobj={}; 
    jobj[x]=sessionStorage.getItem(x); //because key will also occupy some memory
    jsonarr.push(jobj);
    jobj=null;
}
//https://developer.mozilla.org/en/docs/Web/JavaScript/Data_structures 
//JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. 
var size=JSON.stringify(jsonarr).length*2; //16-bit that's why multiply by 2
var arr=["bytes","KB","MB","GB","TB"]; // Define Units
var sizeUnit=0;
while(size>1024){ // To get result in Proper Unit
    sizeUnit++;
    size/=1024;
}
alert(size.toFixed(2)+" "+arr[sizeUnit]);

//Memory occupy by both key and value so Updated Code.

var jsonarr=[];
var jobj=null;
for(x in sessionStorage) // Iterate through each session key
{
    jobj={}; 
    jobj[x]=sessionStorage.getItem(x); //because key will also occupy some memory
    jsonarr.push(jobj);
    jobj=null;
}
//https://developer.mozilla.org/en/docs/Web/JavaScript/Data_structures 
//JavaScript's String type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. 
var size=JSON.stringify(jsonarr).length*2; //16-bit that's why multiply by 2
var arr=["bytes","KB","MB","GB","TB"]; // Define Units
var sizeUnit=0;
while(size>1024){ // To get result in Proper Unit
    sizeUnit++;
    size/=1024;
}
alert(size.toFixed(2)+" "+arr[sizeUnit]);
不知所踪 2024-10-13 16:25:12
window.localStorage.remainingSpace
window.localStorage.remainingSpace
红焚 2024-10-13 16:25:11

在 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")); 

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

PPS 应该在 Chrome 和 Firefox 中工作。

Execute this snippet in JavaScript console (one line version):

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)

P.P.S. Should work both in Chrome and Firefox.

残花月 2024-10-13 16:25:11

根据 @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)';
    };

我的返回:“30.896484375 KB”

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:

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"

甜柠檬 2024-10-13 16:25:11

您可以使用 Blob 功能。 这可能在旧浏览器中不起作用,请检查对 新 Blob 的支持Object.values() 在卡尼乌斯。

示例:

return new Blob(Object.values(localStorage)).size;

Object.values() 将 localStorage 对象转换为数组。 Blob 将数组转换为原始数据。

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.

Example:

return new Blob(Object.values(localStorage)).size;

Object.values() turns the localStorage object to an array. Blob turns the array into raw data.

蓝礼 2024-10-13 16:25:11

IE 有一个 remainingSpace 属性存储对象。目前其他浏览器还没有类似的功能。

我相信默认的空间量是 5MB,尽管我没有亲自测试过。

IE has a remainingSpace property of the Storage object. The other browsers have no equivalent at this time.

I believe that the default amount of space is 5MB, although I have not tested it personally.

新一帅帅 2024-10-13 16:25:11

这是一个简单的示例,说明如何执行此操作,并且应该适用于每个浏览器

alert(1024 * 1024 * 5 - unescape(encodeURIComponent(JSON.stringify(localStorage))).length);

Here is a simple example of how to do this and should work with every browser

alert(1024 * 1024 * 5 - unescape(encodeURIComponent(JSON.stringify(localStorage))).length);
老旧海报 2024-10-13 16:25:11

希望这对某人有帮助。

因为 jsfiddle 上的 Jas- 示例对我不起作用,所以我想出了这个解决方案。
(感谢 Serge Seletskyy 和 Shourav 在下面的代码中使用了他们的位)

下面的函数可用于测试 localStorage 有多少可用空间以及(如果 ls 中已有任何键)还剩多少空间。

这有点暴力,但几乎适用于所有浏览器……除了 Firefox。
在桌面 FF 中,它需要很长时间(4-5 分钟)才能完成,而在 Android 上,它只会崩溃。

该函数下面是我在不同平台上的不同浏览器中所做的测试的简短摘要。享受!

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
}

正如上面所承诺的,在不同浏览器中进行了一些测试:

GalaxyTab 10.1

  • Maxthon Pad 1.7 ~1130ms 5Mb
  • Firefox 20.0(Beta 20.0) 使
  • Chrome 25.0.1364.169 ~22250ms /5Mb
  • Native(标识为 Safari 4.0/Webkit534.5)崩溃。 30) ~995ms /5Mb

iPhone 4s iOS 6.1.3

  • Safari ~ 520ms /5Mb
  • 作为 HomeApp ~525ms / 5Mb
  • iCab ~ 710ms /5mb

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(在抱怨脚本运行时间过长之后)

iPad 3 iOS 6.1.3

  • Safari ~430ms /5Mb
  • iCab ~595ms /5mb

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 (抱怨脚本运行时间太长之后)
  • IE9 ~17900ms /9.54Mb (如果代码中有任何 console.logs 在打开 DevTools 之前不起作用)
  • Opera 12.15 ~4212ms /3.55Mb (这是 5Mb 时的情况)被选中,但 Opera 很好地询问我们是否要增加 ls 的数量,不幸的是,如果连续进行几次测试,它会崩溃)

Win 8(在 Parallels 8 下)

  • IE10 ~7850ms /9.54Mb

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)

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.

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.

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

  • 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

iPhone 4s iOS 6.1.3

  • Safari ~ 520ms /5Mb
  • As HomeApp ~525ms / 5Mb
  • iCab ~ 710ms /5mb

MacBook Pro OSX 1.8.3 (Core 2 Duo 2.66 8Gb memory)

  • 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)

iPad 3 iOS 6.1.3

  • Safari ~430ms /5Mb
  • iCab ~595ms /5mb

Windows 7 -64b (Core 2 Duo 2.93 6Gb memory)

  • 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)

Win 8 (Under Parallels 8)

  • IE10 ~7850ms /9.54Mb
猫弦 2024-10-13 16:25:11

您可以通过以下方法计算您的本地存储:

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());

最终大小(以字节为单位)将记录在浏览器中。

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.

羁〃客ぐ 2024-10-13 16:25:11

我解决这个问题的方法是创建函数来查找本地存储中的已用空间和剩余空间,然后创建一个调用这些函数来确定最大存储空间的函数。

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'));
            
            //Recommended by @pkExec and @jrob007
            localStorage.setItem(testQuotaKey, String('1').repeat(tryByteSize));
            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;
}

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'));
            
            //Recommended by @pkExec and @jrob007
            localStorage.setItem(testQuotaKey, String('1').repeat(tryByteSize));
            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;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文