Coder Perfect

How do I figure out how big my localStorage is?

Problem

I’m currently working on a site that will employ HTML5’s localStorage feature. I’ve read everything there is to know about browser size limits. However, I’ve yet to come across a method for determining the current size of a localStorage instance. This question appears to imply that JavaScript lacks a built-in method for displaying the size of a variable. Is there a memory size property for localStorage that I’m not aware of? Is there a simple way to accomplish this that I’m overlooking?

Because my site is designed to allow visitors to add information in a ‘offline’ mode, being able to notify them when the storage space is nearly filled is critical.

Asked by derivation

Solution #1

Use the JavaScript console to run the following snippet:

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


For the sake of readability, the same code is repeated in multiple lines.

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 put this text in the ‘location’ field of a bookmark for easy access.

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. It should work on Chrome and Firefox as well.

Answered by Sergiy Seletskyy

Solution #2

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

“30.896484375 KB” was the result for me.

Answered by tennisgent

Solution #3

The Blob function can be used to determine the current size of local storage data. Check the support for new Blob and Object.values() at caniuse to see if this works in older browsers.

Example:

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

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

Answered by P Roitto

Solution #4

The Storage object in Internet Explorer has a remainingSpace property. At present time, there is no equivalent in the other browsers.

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

Answered by Adam

Solution #5

I hope this information is useful to someone.

I came up with this approach because the Jas- example on jsfiddle does not work for me. (I used parts of Serge Seletskyy’s and Shourav’s code in the code below.)

The function below can be used to determine how much space is available for localStorage and how much space is remaining (if any keys are already in lS).

It’s a bit brute force, but it works in almost all browsers… except Firefox. On the desktop, it takes a long time (4-5 minutes) to complete, and on Android, it simply crashes.

Below the function is a quick overview of tests I’ve run in various browsers and on various systems. 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, some tests in several browsers:

GalaxyTab 10.1

iOS 6.1.3 for iPhone 4s

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

iOS 6.1.3 for iPad 3

64-bit version of Windows 7 (Core 2 Duo 2.93 6Gb memory)

8 victories (Under Parallels 8)

Answered by Jakub Gadkowski

Post is based on https://stackoverflow.com/questions/4391575/how-to-find-the-size-of-localstorage