Any idea how to check the remaining storage space in an HTML5 localstorage data store?
4 Answers
I don't know if this helps, but you can check if it full.
“QUOTA_EXCEEDED_ERR” is the exception that will get thrown if you exceed your storage quota of 5 megabytes.
And this other answer might be related.
-
2Why shrink the URL? StackOverflow can't detect the link to put it in the linked questions on the right.– Zan LynxCommented Mar 4, 2011 at 3:22
Default localStorage allocated size is: 5Mb
var allocated = 5;
var total = 0;
for(var x in localStorage){
var amount = (localStorage[x].length * 2) / 1024 / 1024;
total += amount;
}
var remaining = allocated - total;
console.log( "Used: " + total + " MB");
console.log( "Remaining: " + remaining + " MB");
-
1Doesn't this entirely depend on the character encoding? This assumes each character is 2 bytes.– micahCommented Nov 20, 2014 at 16:30
5 megabytes by default. It will throw “QUOTA_EXCEEDED_ERR” exception if storage exceeds more than of 5 megabytes.
-
1It depends on the browser. 5MB is common but so is 2.5MB and unlimited: dev-test.nemikor.com/web-storage/support-test– tagawaCommented Feb 10, 2012 at 6:48
You could implent a lookup table of "nominal limits" after detecting the browser, and substract the key-value pair size of what's already in the localStorage from it.
-
@PederRice If I wasn't a bit too busy at the moment I'd hack some code up, but my basic idea is that if you know the user is running for example Chrome (I've used an adaptation of this in the past), then you would look up the limit on a LUT (in this case, an object that maps browser versions to storage limits), it would be 5MB (unless it's an extension and has unlimited localStorage permissions), then you would measure what you already have (still, maybe adding up the strings' sizes could be naive if they're UTF-8) and substract from the total. Commented Feb 28, 2012 at 2:57
-
1By the way you may want to know that IE8 supports
localStorage.remainingSpace
. Commented Feb 28, 2012 at 3:02