Jak znaleźć Rozmiar localStorage

Obecnie rozwijam stronę, która będzie korzystać z localStorage HTML5. Przeczytałem wszystko o ograniczeniach rozmiaru dla różnych przeglądarek. Jednak nie widziałem nic na temat tego, jak dowiedzieć się o aktualnym rozmiarze wystąpienia localStorage. to pytanie wydaje się wskazywać, że JavaScript nie ma wbudowanego sposobu pokazywania wielkości danej zmiennej. Czy localStorage ma właściwość rozmiaru pamięci, której nie widziałem? Czy jest na to łatwy sposób, że jestem zaginęła?

Moja strona ma na celu umożliwienie użytkownikom wprowadzania informacji w trybie "offline", więc bardzo ważne jest, aby móc dać im ostrzeżenie, gdy pamięć jest prawie pełna.

Author: Community, 2010-12-08

13 answers

Wykonaj ten fragment w konsoli Chrome

var _lsTotal=0,_xLen,_x;for(_x in localStorage){_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");

Lub dodaj ten tekst w polu "Lokalizacja" zakładki dla wygodnego użycia

javascript: var x, xLen, log=[],total=0;for (x in localStorage){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. fragmenty są aktualizowane zgodnie z prośbą w komentarzu. Teraz obliczenia obejmują długość samego klucza. Każda długość jest mnożona przez 2, ponieważ znak w javascript przechowuje się jako UTF-16 (zajmuje 2 bajty)

 141
Author: Serge Seletskyy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-29 23:23:58

Wychodząc z tego, co @Shourav powiedział powyżej, napisałem małą funkcję, która powinna dokładnie pobrać wszystkie klucze localStorage (dla bieżącej domeny) i obliczyć łączny rozmiar, abyś wiedział dokładnie, ile pamięci zajmuje Twój obiekt 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"

 38
Author: tennisgent,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-26 17:54:09

IE posiada właściwość remainingSpace obiektu Storage. W innych przeglądarkach nie ma obecnie odpowiednika.

Uważam, że domyślna ilość miejsca to 5MB, chociaż osobiście tego nie testowałem.

 15
Author: Adam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-08 19:49:21

Oto prosty przykład Jak to zrobić i powinien działać z każdą przeglądarką

alert(1024 * 1024 * 5 - unescape(encodeURIComponent(JSON.stringify(localStorage))).length);
 12
Author: jas-,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-11 11:56:28

Mam nadzieję, że to komuś pomoże.

Ponieważ Jas-przykład na jsfiddle nie działa dla mnie, wymyśliłem takie rozwiązanie. (podziękowania dla Serge Seletskyy i Shourav za ich bity użyłem w kodzie poniżej)

Poniżej znajduje się funkcja, która może być użyta do sprawdzenia, ile miejsca jest dostępne dla localStorage i (jeśli jakiekolwiek klucze są już w lS), ile miejsca zostało.

Jest to trochę brutalna siła, ale działa prawie w każdej przeglądarce... oprócz Firefoksa. NO w desktopie FF potrzeba wiek (4-5min), aby zakończyć, a na Androidzie po prostu się zawiesza.

Pod funkcją znajduje się krótkie podsumowanie testów, które wykonałem w różnych przeglądarkach na różnych platformach. Smacznego!

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
}

I zgodnie z obietnicą powyżej jakiś test w różnych przeglądarkach:

GalaxyTab 10.1

  • Maxthon Pad 1.7 ~1130ms 5Mb
  • Firefox 20.0 (Beta 20.0) rozbił oba
  • Chrome 25.0.1364.169 ~22250ms / 5MB
  • Native (identyfikuje się jako 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 (pamięć Core 2 Duo 2.66 8GB)

  • Safari 6.0.3 ~105ms / 5MB
  • Chrome 26.0.1410.43 ~ 3400ms / 5MB
  • Firefox 20.0 300150ms (!) / 10Mb (po narzekaniu na działanie skryptu na long)

IPad 3 iOS 6.1.3

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

Windows 7-64B (pamięć Core 2 Duo 2.93 6GB)

  • Safari 5.1.7 ~ 80ms / 5MB
  • Chrome 26.0.1410.43 ~1220ms / 5MB
  • Firefox 20.0 228500ms (!) / 10Mb (po narzekaniu na działanie skryptu na long)
  • IE9 ~ 17900MS / 9.54 Mb (jeśli jakaś konsola.logi są w kodzie nie działa dopóki DevTools nie są otwarte)
  • Opera 12.15 ~ 4212ms / 3,55 Mb (jest to Po wybraniu 5MB, ale Opera ładnie pyta, czy chcemy zwiększyć ilość lS, niestety zawiesza się, jeśli test został przeprowadzony kilka razy z rzędu)

Win 8 (Under Parallels 8)

  • IE10 ~7850MS /9,54 Mb
 10
Author: Jakub Gadkowski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-04 16:44:13

Możesz obliczyć localstorage za pomocą następujących metod:

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

Wreszcie rozmiar w bajtach zostanie zalogowany w przeglądarce.

 5
Author: Usman Faisal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-11 11:04:49

Użyłbym kodu @ tennisgen, który pobiera wszystkie i liczy zawartość, ale liczę same klucze:

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)';
    };
 3
Author: Arnaud Valensi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-30 22:02:10

Oprócz odpowiedzi @serge, która jest najczęściej głosowana tutaj, rozmiar kluczy należy wziąć pod uwagę. Poniższy kod doda rozmiar kluczy przechowywanych w localStorage

var t = 0; 
for (var x in localStorage) { 
    t += (x.length + localStorage[x].length) * 2; 
} 
console.log((t / 1024) + " KB");
 2
Author: Mihir,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-19 14:26:59

Zgodnie ze specyfikacją, każdy znak łańcucha ma 16 bitów.

Ale sprawdzenie za pomocą chrome (Ustawienia>Ustawienia treści>Pliki cookie i dane witryny) pokazuje nam, że inicjowanie localStorage zajmuje 3kB (rozmiar nadmiarowy)

I rozmiar przechowywanych danych jest zgodny z tą relacją (z dokładnością do 1kB)
3 + ((localStorage.x. Długość*16)/(8*1024)) kB

Gdzie localStorage.x to Twój ciąg pamięci.

 1
Author: Shourav Bin Rabbani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-26 16:40:21

Sposób, w jaki zająłem się tym problemem, polega na stworzeniu funkcji do wyszukiwania używanej przestrzeni i pozostałej przestrzeni w pamięci lokalnej, a następnie funkcji, która wywołuje te funkcje w celu określenia maksymalnej przestrzeni dyskowej.

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;
}
 1
Author: Jed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-13 23:43:16

/ / Pamięć zajmuje zarówno klucz, jak i wartość, więc zaktualizowany Kod.

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]);
 0
Author: Dipak Prajapati,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-29 04:44:00

Można uzyskać bieżący rozmiar danych pamięci lokalnej za pomocą funkcji Blob . to może nie działać w starych przeglądarkach.

Przykład:

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

Obiekt.values() zamienia obiekt localStorage w tablicę. Blob zamienia tablicę w surowe dane.

 0
Author: P Roitto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-10 08:50:08
window.localStorage.remainingSpace
 -1
Author: Pradeep Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-08 19:48:34