Calculating usage of localStorage space

后端 未结 12 1466
悲哀的现实
悲哀的现实 2020-11-27 10:28

I am creating an app using the Bespin editor and HTML5\'s localStorage. It stores all files locally and helps with grammar, uses JSLint and some other parsers for CSS and HT

相关标签:
12条回答
  • 2020-11-27 10:42

    I needed to actually simulate and test what my module will do when storage is full, so I needed to get a close precision on when the storage is full, rather than the accepted answer, which loses that precision at a rate of i^2.

    Here's my script, which should always produce a precision of 10 on when memory cap is reached, and fairly quickly despite having some easy optimizations... EDIT: I made the script better and with an exact precision:

    function fillStorage() {
        var originalStr = "1010101010";
        var unfold = function(str, times) {
            for(var i = 0; i < times; i++)
                str += str;
            return str;
        }
        var fold = function(str, times) {
            for(var i = 0; i < times; i++) {
                var mid = str.length/2;
                str = str.substr(0, mid);
            }
            return str;
        }
    
        var runningStr = originalStr;
        localStorage.setItem("filler", runningStr);
        while(true) {
            try {
                runningStr = unfold(runningStr, 1);
                console.log("unfolded str: ", runningStr.length)
                localStorage.setItem("filler", runningStr);
            } catch (err) {
                break;
            }
        }
    
        runningStr = fold(runningStr, 1);  
        var linearFill = function (str1) {
            localStorage.setItem("filler", localStorage.getItem("filler") + str1);
        }
        //keep linear filling until running string is no more...
        while(true) {
            try {
                linearFill(runningStr)
            } catch (err) {
                runningStr = fold(runningStr, 1);
                console.log("folded str: ", runningStr.length)
                if(runningStr.length == 0)
                    break;
            }
        }
    
        console.log("Final length: ", JSON.stringify(localStorage).length)
    }
    
    0 讨论(0)
  • 2020-11-27 10:44

    You can use the below line to accurately calculate this value and here is a jsfiddle for illustration of its use

    alert(1024 * 1024 * 5 - escape(encodeURIComponent(JSON.stringify(localStorage))).length);
    
    0 讨论(0)
  • 2020-11-27 10:44

    To add to the browser test results:

    Firefox i=22.

    Safari Version 5.0.4 on my Mac didn't hang. Error as Chrome. i=21.

    Opera Tells the user that the website wants to store data but doesn't have enough space. The user can reject the request, up the limit to the amount required or to several other limits, or set it to unlimited. Go to opera:webstorage to say whether this message appears or not. i=20. Error thrown is same as Chrome.

    IE9 standards mode Error as Chrome. i=22.

    IE9 in IE8 standards mode Console message "Error: Not enough storage is available to complete this operation". i=22

    IE9 in older modes object error. i=22.

    IE8 Don't have a copy to test, but local storage is supported (http://stackoverflow.com/questions/3452816/does-ie8-support-out-of-the-box-in-localstorage)

    IE7 and below Doesn't support local storage.

    0 讨论(0)
  • 2020-11-27 10:45

    You may be able to get an approximate idea by using the JSON methods to turn the whole localStorage object to a JSON string:

    JSON.stringify(localStorage).length
    

    I don't know how byte-accurate it would be, especially with the few bytes of added markup if you're using additional objects - but I figure it's better than thinking you're only pushing 28K and instead doing 280K (or vice-versa).

    0 讨论(0)
  • 2020-11-27 10:47

    This might help somebody. In chrome is possible to ask the user to allow to use more disk space if needed:

    // Request Quota (only for File System API)  
    window.webkitStorageInfo.requestQuota(PERSISTENT, 1024*1024, function(grantedBytes) {
      window.webkitRequestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler); 
    }, function(e) {
      console.log('Error', e); 
    });
    

    Visit https://developers.google.com/chrome/whitepapers/storage#asking_more for more info.

    0 讨论(0)
  • 2020-11-27 10:50

    This function gets the exact storage available / left:

    I made a suite of useful functions for localStorage *here*

    http://jsfiddle.net/kzq6jgqa/3/

    function getLeftStorageSize() {
        var itemBackup = localStorage.getItem("");
        var increase = true;
        var data = "1";
        var totalData = "";
        var trytotalData = "";
        while (true) {
            try {
                trytotalData = totalData + data;
                localStorage.setItem("", trytotalData);
                totalData = trytotalData;
                if (increase) data += data;
            } catch (e) {
                if (data.length < 2) break;
                increase = false;
                data = data.substr(data.length / 2);
            }
        }
        localStorage.setItem("", itemBackup);
    
        return totalData.length;
    }
    
    // Examples
    document.write("calculating..");
    var storageLeft = getLeftStorageSize();
    console.log(storageLeft);
    document.write(storageLeft + "");
    
    // to get the maximum possible *clear* the storage 
    localStorage.clear();
    var storageMax = getLeftStorageSize();
    

    Note, that this is not very quick, so don't use it all the time.

    With this I also found out that: the Item-Name will take up as much space as its length, the Item-Value will also take up as much space as their length.

    Maximum storage I got - all about 5M:

    • 5000000 chars - Edge
    • 5242880 chars - Chrome
    • 5242880 chars - Firefox
    • 5000000 chars - IE

    You will find some out-commented code in the fiddle to see the progress in the console.

    Took me some time to make, hope this helps ☺

    0 讨论(0)
提交回复
热议问题