Cómo encontrar el tamaño de localStorage


Actualmente estoy desarrollando un sitio que hará uso del localStorage de HTML5. He leído todo sobre las limitaciones de tamaño para diferentes navegadores. Sin embargo, no he visto nada sobre cómo averiguar el tamaño actual de una instancia de localStorage. Esta pregunta parece indicar que JavaScript no tiene una forma incorporada de mostrar el tamaño de una variable dada. ¿localStorage tiene una propiedad de tamaño de memoria que no he visto? Hay una manera fácil de hacer esto que estoy ¿desaparecido?

Mi sitio está destinado a permitir a los usuarios ingresar información en un modo 'offline', por lo que es muy importante poder darles una advertencia cuando el almacenamiento está casi lleno.

Author: Community, 2010-12-08

13 answers

Ejecuta este fragmento en Chrome console

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

O agregue este texto en el campo 'ubicación' de un marcador para un uso conveniente

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.d. Los fragmentos de código se actualizan según lo solicitado en el comentario. Ahora el cálculo incluye la longitud de la clave en sí. Cada longitud se multiplica por 2 porque el char en javascript se almacena como UTF-16 (ocupa 2 bytes)

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-29 23:23:58

Saliendo de lo que @Shourav dijo anteriormente, escribí una pequeña función que debería capturar con precisión todas sus teclas localStorage (para el dominio actual) y calcular el tamaño combinado para que sepa exactamente cuánta memoria ocupa su objeto 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)';
    };

La mina regresó: "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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-26 17:54:09

IE tiene una propiedad remainingSpace del objeto de almacenamiento. Los otros navegadores no tienen equivalente en este momento.

Creo que la cantidad predeterminada de espacio es de 5MB, aunque no lo he probado personalmente.

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-08 19:49:21

Aquí hay un simple ejemplo de cómo hacer esto y debería funcionar con todos los navegadores

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-11 11:56:28

Espero que esto ayude a alguien.

Debido a que Jas - example en jsfiddle no funciona para mí, se me ocurrió esta solución. (gracias a Serge Seletskyy y Shourav por sus bits que utilicé en el código a continuación)

A continuación se muestra la función que se puede usar para probar cuánto espacio está disponible para localStorage y (si alguna tecla ya está en lS) cuánto espacio queda.

Es un poco de fuerza bruta, pero funciona en casi todos los navegadores... aparte de Firefox. Bueno, en el escritorio FF se necesita edades (4-5min) para completar, y en Android simplemente se bloquea.

Debajo de la función hay un breve resumen de las pruebas que he realizado en diferentes navegadores en diferentes plataformas. ¡Que lo disfrutes!

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
}

Y como se prometió anteriormente alguna prueba en diferentes navegadores:

GalaxyTab 10.1

  • Maxthon Pad 1.7 ~1130ms 5Mb
  • Firefox 20.0 (Beta 20.0) se estrelló tanto
  • Cromo 25.0.1364.169 ~22250ms /5Mb
  • Nativo (se identifica como Safari 4.0 / Webkit534. 30) ~995ms /5Mb

IPhone 4s iOS 6.1.3

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

MacBook Pro OSX 1.8.3 (Core 2 Duo 2.66 8gb de memoria)

  • Safari 6.0.3 ~105ms / 5Mb
  • Cromo 26.0.1410.43 ~3400ms / 5Mb
  • Firefox 20.0 300150ms (!) / 10Mb (después de quejarse de que el script se ejecuta a largo)

IPad 3 iOS 6.1.3

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

Windows 7 - 64b (Core 2 Duo 2.93 6GB de memoria)

  • Safari 5.1.7 ~80ms / 5Mb
  • Cromo 26.0.1410.43 ~1220ms / 5Mb
  • Firefox 20.0 228500ms (!) / 10Mb (después de quejarse de que el script se ejecuta a largo)
  • IE9 ~17900ms /9.54 Mb ( si alguna consola.los registros están en el código no funciona hasta que se abren DevTools)
  • Opera 12.15 ~4212ms / 3.55 Mb (esto es cuando se selecciona 5Mb, pero Opera pregunta muy bien si queremos aumentar la cantidad de lS, desafortunadamente se bloquea si la prueba se realiza un par de veces seguidas)

Win 8 (Bajo 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-04 16:44:13

Puede calcular su almacenamiento local mediante los siguientes métodos:

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

Finalmente el tamaño en bytes se registrará en el navegador.

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-11 11:04:49

Usaría el código de @ tennisgen que obtiene todo y cuenta el contenido, pero cuento las claves mismas:

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-30 22:02:10

Además de la respuesta de @serge que es la más votada aquí, el tamaño de las claves debe ser considerado. El siguiente código agregará el tamaño de las claves almacenadas en 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-19 14:26:59

Como dice la especificación, cada carácter de una cadena es de 16 bits.

Pero inspeccionar con chrome (Configuración>Configuración de contenido>Cookies y datos del sitio) nos muestra que iniciar localStorage toma 3kB (tamaño de sobrecarga)

Y el tamaño de los datos almacenados sigue esta relación (con una precisión de 1kB)
3 + ((Almacenamiento local.x. longitud*16)/(8*1024)) kB

Donde localStorage.x es tu cadena de almacenamiento.

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-26 16:40:21

La forma en que abordé este problema es crear funciones para averiguar el espacio utilizado y el espacio restante en el almacenamiento local y luego una función que llame a esas funciones para determinar el espacio de almacenamiento máximo.

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-13 23:43:16

//La memoria ocupa tanto la clave como el valor del Código actualizado.

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-29 04:44:00

Puede obtener el tamaño actual de los datos de almacenamiento local utilizando la función Blob . Esto puede no funcionar en navegadores antiguos.

Ejemplo:

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

Objeto.values () convierte el objeto localStorage en una matriz. Blob convierte la matriz en datos sin procesar.

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-12-08 19:48:34