How to find the size of localStorage

2019-01-05 08:43发布

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.

13条回答
我欲成王,谁敢阻挡
2楼-- · 2019-01-05 08:51

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-01-05 08:54

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)';
    };
查看更多
Viruses.
4楼-- · 2019-01-05 08:56

You can get the current size of the local storage data using the Blob function. This may not work in old browsers.

Example:

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

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

查看更多
虎瘦雄心在
5楼-- · 2019-01-05 08:59
window.localStorage.remainingSpace
查看更多
不美不萌又怎样
6楼-- · 2019-01-05 09:00

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
查看更多
女痞
7楼-- · 2019-01-05 09:00

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");
查看更多
登录 后发表回答