javascriptsizestoragelocal-storagecapacity

Calculating usage of localStorage space


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 HTML to aid the user.

I want to calculate how much of the localStorage limit has been used and how much there actually is. Is this possible today? I was thinking for not to simply calculate the bits that are stored. But then again I'm not sure what more is there that I can't measure myself.


Solution

  • I didn't find a universal way to get the remaining limit on the browsers I needed, but I did find out that when you do reach the limit there is an error message that pops up. This is of-course different in each browser.

    To max it out I used this little script:

    for (var i = 0, data = "m"; i < 40; i++) {
        try { 
            localStorage.setItem("DATA", data);
            data = data + data;
        } catch(e) {
            var storageSize = Math.round(JSON.stringify(localStorage).length / 1024);
            console.log("LIMIT REACHED: (" + i + ") " + storageSize + "K");
            console.log(e);
            break;
        }
    }
    localStorage.removeItem("DATA");
    

    From that I got this information:

    Google Chrome

    Mozilla Firefox

    Safari

    Internet Explorer, Edge (community)


    My solution

    So far my solution is to add an extra call each time the user would save anything. And if the exception is caught then I would tell them that they are running out of storage capacity.


    Edit: Delete the added data

    I forgot to mention that for this to actually work you would need to delete the DATA item that was set originally. The change is reflected above by using the removeItem() function.