views:

472

answers:

2

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.

+2  A: 

IE8 implements the remainingSpace property for this purpose:

alert(window.localStorage.remainingSpace);  // should return 5000000 when empty

Unfortunately it seems that this is not available in the other browsers. However I am not sure if they implement something similar.

Daniel Vassallo
THanks! :D Hehe...thats fun for them. Unfortunately my apps currently are only tested in Safari, Chrome, Firefox. Thanks for the info :D
WmasterJ
@WmasterJ: I'm seeing that the IE Team actually proposed for this (or something similar) to be included in the standard (back in 2008): http://markmail.org/thread/ugzdcamtyftcyk6y.
Daniel Vassallo
This time IE was right. It would seem obvious that this is needed.
WmasterJ
+3  A: 

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:

localStorage.setItem("DATA", "m");
for(i=0 ; i<40 ; i++) {
    var data = localStorage.getItem("DATA");
    try { 
        localStorage.setItem("DATA", data + data);
    } catch(e) {
        console.log("LIMIT REACHED: (" + i + ")");
        console.log(e);
    }
}
localStorage.removeItem("DATA");

From that I got this information:

Google Chrome

  • DOMException:
    • code: 22
    • message: "QUOTA_EXCEEDED_ERR: DOM Exception 22"
    • name: "QUOTA_EXCEEDED_ERR"

Mozilla Firefox

  • DOMException:
    • code: 1014
    • message: "Persistent storage maximum size reached"
    • name: "NS_ERROR_DOM_QUOTA_REACHED"

Safari

  • Crashed (almost, took about 4 min to recover)

Internet Explorer (community)

  • Anyone wanna to try? (I'm on a Mac, no Windows)

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.

WmasterJ
Very nice, what was the value of `i` when this was reached in each case?
artlung
20-21 i think. You can run the test yourself if you want to.
WmasterJ