localStorage值的最大大小是多少?

时间:2010-06-07 12:09:16

标签: javascript html5 local-storage

由于localStorage(当前)仅支持字符串作为值,并且为了做到这一点,对象需要在存储之前进行字符串化(存储为JSON字符串),是否存在定义的限制值的长度。

有没有人知道是否有适用于所有浏览器的定义?

13 个答案:

答案 0 :(得分:378)

引用Wikipedia article on Web Storage

  

可以简单地查看网络存储,作为对Cookie的改进,提供更大的存储容量(每个来源10 MB在Google Chrome(https://plus.google.com/u/0/+FrancoisBeaufort/posts/S5Q9HqDB8bh),Mozilla Firefox和Opera;每个存储区10 MB在Internet Explorer )和更好的编程接口。

并引用John Resig article [2007年1月发布]:

  

存储空间

     

暗示,使用DOM存储,   你有更多的存储空间   空间比典型的用户代理   对Cookies的限制。   但是,提供的金额   未在规范中定义,   也没有有意义的广播   用户代理。

     

如果你看一下Mozilla源代码   我们可以看到5120KB是默认值   整个域的存储大小。   这为您提供了更多空间   与典型的2KB工作   cookie中。

     

但是,此存储区域的大小   可以由用户自定义(所以a   不保证5MB存储区域,   也不暗示)和用户代理   (例如,Opera可能只提供   3MB - 但只有时间会证明。)

答案 1 :(得分:121)

实际上Opera没有5MB的限制。它提供了增加限制,因为应用程序需要更多。用户甚至可以为域选择“无限存储”。

您可以轻松test localStorage limits/quota自己。

答案 2 :(得分:66)

这是一个直截了当的查找限制的脚本:

if (localStorage && !localStorage.getItem('size')) {
    var i = 0;
    try {
        // Test up to 10 MB
        for (i = 250; i <= 10000; i += 250) {
            localStorage.setItem('test', new Array((i * 1024) + 1).join('a'));
        }
    } catch (e) {
        localStorage.removeItem('test');
        localStorage.setItem('size', i - 250);            
    }
}

此处有the gistJSFiddleblog post

该脚本将测试设置越来越大的文本字符串,直到浏览器抛出异常。此时它将清除测试数据并在localStorage中设置一个大小键,以千字节为单位存储大小。

答案 3 :(得分:24)

不要假设5MB可用 - localStorage容量因浏览器而异,2.5MB,5MB且无限制是最常见的值。 资料来源:http://dev-test.nemikor.com/web-storage/support-test/

答案 4 :(得分:24)

查找可以存储在localStorage

中的单个字符串的最大长度

此代码段将找到可以存储在每个域localStorage中的字符串的最大长度。

//Clear localStorage
for (var item in localStorage) delete localStorage[item];

window.result = window.result || document.getElementById('result');

result.textContent = 'Test running…';

//Start test
//Defer running so DOM can be updated with "test running" message
setTimeout(function () {

    //Variables
    var low = 0,
        high = 2e9,
        half;

    //Two billion may be a little low as a starting point, so increase if necessary
    while (canStore(high)) high *= 2;


    //Keep refining until low and high are equal
    while (low !== high) {
        half = Math.floor((high - low) / 2 + low);

        //Check if we can't scale down any further
        if (low === half || high === half) {
            console.info(low, high, half);
            //Set low to the maximum possible amount that can be stored 
            low = canStore(high) ? high : low;
            high = low;
            break;
        }


        //Check if the maximum storage is no higher than half
        if (storageMaxBetween(low, half)) {
            high = half;
            //The only other possibility is that it's higher than half but not higher than "high"
        } else {
            low = half + 1;
        }

    }

    //Show the result we found!
    result.innerHTML = 'The maximum length of a string that can be stored in localStorage is <strong>' + low + '</strong> characters.';

    //Functions
    function canStore(strLen) {
        try {
            delete localStorage.foo;
            localStorage.foo = Array(strLen + 1).join('A');
            return true;
        } catch (ex) {
            return false;
        }
    }


    function storageMaxBetween(low, high) {
        return canStore(low) && !canStore(high);
    }

}, 0);
<h1>LocalStorage single value max length test</h1>

<div id='result'>Please enable JavaScript</div>

请注意,字符串的长度在JavaScript中是有限的;如果您想查看localStorage中可以存储的最大数据量(不限于单个字符串),则为can use the code in this answer

修改:堆栈代码段不支持localStorage,所以here is a link to JSFiddle

结果

Chrome(45.0.2454.101): 5242878个字符
Firefox(40.0.1): 5242883个字符
Internet Explorer(11.0.9600.18036) 16386 122066 122070个字符

我在Internet Explorer的每次运行中得到不同的结果。

答案 5 :(得分:22)

移动浏览器:

Browser    | Chrome    | Android Browser    | Firefox     | iOS Safari
Version    | 40        | 4.3                | 34          | 6-8
Available  | 10MB      | 2MB                | 10MB        | 5MB

桌面浏览器:

Browser    | Chrome   | Opera    | Firefox    | Safari      | IE
Version    | 40       | 27       | 34         | 6-8         | 9-11
Available  | 10MB     | 10MB     | 10MB       | 5MB         | 10MB

Reference Link

答案 6 :(得分:13)

您不希望将大型对象字符串化为单个localStorage条目。这将是非常低效的 - 每次细微的细节变化时,整个事情都必须被解析和重新编码。此外,JSON无法处理对象结构中的多个交叉引用,并清除了大量细节,例如:构造函数,数组的非数字属性,稀疏条目中的内容等。

相反,您可以使用Rhaboo。它使用大量localStorage条目存储大型对象,因此您可以快速进行小的更改。恢复的对象是保存的对象的更准确的副本,API非常简单。 E.g:

var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
store.write('somethingfancy', {
  one: ['man', 'went'],
  2: 'mow',
  went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');

BTW,我写了。

答案 7 :(得分:6)

我真的很喜欢cdmckay's answer,但实时查看大小并不是很好看:它太慢了(对我来说是2秒)。这是改进版本,它更快,更精确,也可以选择错误的大小(默认$('yourSelector').selectpicker({ dropupAuto: false });,错误越小 - 计算时间越长):

250,000

测试:

function getLocalStorageMaxSize(error) {
  if (localStorage) {
    var max = 10 * 1024 * 1024,
        i = 64,
        string1024 = '',
        string = '',
        // generate a random key
        testKey = 'size-test-' + Math.random().toString(),
        minimalFound = 0,
        error = error || 25e4;

    // fill a string with 1024 symbols / bytes    
    while (i--) string1024 += 1e16;

    i = max / 1024;

    // fill a string with 'max' amount of symbols / bytes    
    while (i--) string += string1024;

    i = max;

    // binary search implementation
    while (i > 1) {
      try {
        localStorage.setItem(testKey, string.substr(0, i));
        localStorage.removeItem(testKey);

        if (minimalFound < i - error) {
          minimalFound = i;
          i = i * 1.5;
        }
        else break;
      } catch (e) {
        localStorage.removeItem(testKey);
        i = minimalFound + (i - minimalFound) / 2;
      }
    }

    return minimalFound;
  }
}

这对标准错误的速度要快得多;在必要时它也可以更精确。

答案 8 :(得分:6)

我写了这个简单的代码来测试localStorage大小(以字节为单位)。

https://github.com/gkucmierz/Test-of-localStorage-limits-quota

const check = bytes => {
  try {
    localStorage.clear();
    localStorage.setItem('a', '0'.repeat(bytes));
    localStorage.clear();
    return true;
  } catch(e) {
    localStorage.clear();
    return false;
  }
};

Github页面:

https://gkucmierz.github.io/Test-of-localStorage-limits-quota/

我在台式机chrome,歌剧,firefox,勇敢和移动chrome上的结果相同,约为5Mbytes

enter image description here

再缩小一半会导致safari〜2Mb

enter image description here

答案 9 :(得分:5)

您可以在现代浏览器中使用以下代码,以实时有效地检查存储配额(总计和使用量):

if ('storage' in navigator && 'estimate' in navigator.storage) {
        navigator.storage.estimate()
            .then(estimate => {
                console.log("Usage (in Bytes): ", estimate.usage,
                            ",  Total Quota (in Bytes): ", estimate.quota);
            });
}

答案 10 :(得分:4)

我正在做以下事情:

getLocalStorageSizeLimit = function () {

    var maxLength = Math.pow(2,24);
    var preLength = 0;
    var hugeString = "0";
    var testString;
    var keyName = "testingLengthKey";

    //2^24 = 16777216 should be enough to all browsers
    testString = (new Array(Math.pow(2, 24))).join("X");

    while (maxLength !== preLength) {
        try  {
            localStorage.setItem(keyName, testString);

            preLength = testString.length;
            maxLength = Math.ceil(preLength + ((hugeString.length - preLength) / 2));

            testString = hugeString.substr(0, maxLength);
        } catch (e) {
            hugeString = testString;

            maxLength = Math.floor(testString.length - (testString.length - preLength) / 2);
            testString = hugeString.substr(0, maxLength);
        }
    }

    localStorage.removeItem(keyName);

    maxLength = JSON.stringify(this.storageObject).length + maxLength + keyName.length - 2;

    return maxLength;
};

答案 11 :(得分:3)

我已将二进制测试压缩到我使用的此功能中:

function getStorageTotalSize(upperLimit/*in bytes*/) {
    var store = localStorage, testkey = "$_test"; // (NOTE: Test key is part of the storage!!! It should also be an even number of characters)
    var test = function (_size) { try { store.removeItem(testkey); store.setItem(testkey, new Array(_size + 1).join('0')); } catch (_ex) { return false; } return true; }
    var backup = {};
    for (var i = 0, n = store.length; i < n; ++i) backup[store.key(i)] = store.getItem(store.key(i));
    store.clear(); // (you could iterate over the items and backup first then restore later)
    var low = 0, high = 1, _upperLimit = (upperLimit || 1024 * 1024 * 1024) / 2, upperTest = true;
    while ((upperTest = test(high)) && high < _upperLimit) { low = high; high *= 2; }
    if (!upperTest) {
        var half = ~~((high - low + 1) / 2); // (~~ is a faster Math.floor())
        high -= half;
        while (half > 0) high += (half = ~~(half / 2)) * (test(high) ? 1 : -1);
        high = testkey.length + high;
    }
    if (high > _upperLimit) high = _upperLimit;
    store.removeItem(testkey);
    for (var p in backup) store.setItem(p, backup[p]);
    return high * 2; // (*2 because of Unicode storage)
}

它还会在测试之前备份内容,然后将其还原。

工作原理:将大小增加一倍,直到达到限制或测试失败。然后,它存储高低点之间的距离的一半,并且每次减去/相加一半的一半(减去失败并增加成功);磨成适当的值。

upperLimit默认情况下为1GB,它只是限制在开始二进制搜索之前以指数级向上扫描的距离。我怀疑这甚至需要更改,但是我一直在思考。 ;)

在Chrome上:

> getStorageTotalSize();
> 10485762
> 10485762/2
> 5242881
> localStorage.setItem("a", new Array(5242880).join("0")) // works
> localStorage.setItem("a", new Array(5242881).join("0")) // fails ('a' takes one spot [2 bytes])

IE11,Edge和FireFox也报告相同的最大大小(10485762字节)。

答案 12 :(得分:1)

基于此原因,一旦我开发了 Chrome (桌面浏览器)扩展程序并测试了本地存储实际最大容量。

我的结果:

Ubuntu 18.04.1 LTS (64-bit)
Chrome 71.0.3578.98 (Official Build) (64-bit)
Local Storage content size 10240 KB (10 MB)

使用次数超过10240 KB时,我收到以下错误消息:

  

未捕获的DOMException:无法在“存储”上执行“ setItem”:设置“注释”的值超出了配额。

相关问题