Calculating usage of localStorage space

后端 未结 12 1522
悲哀的现实
悲哀的现实 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: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 ☺

提交回复
热议问题