How to Find the Size of Localstorage

How to find the size of localStorage

Execute this snippet in JavaScript console (one line version):

var _lsTotal=0,_xLen,_x;for(_x in localStorage){ if(!localStorage.hasOwnProperty(_x)){continue;} _xLen= ((localStorage[_x].length + _x.length)* 2);_lsTotal+=_xLen; console.log(_x.substr(0,50)+" = "+ (_xLen/1024).toFixed(2)+" KB")};console.log("Total = " + (_lsTotal / 1024).toFixed(2) + " KB");

The same code in multiple lines for reading sake

var _lsTotal = 0,
_xLen, _x;
for (_x in localStorage) {
if (!localStorage.hasOwnProperty(_x)) {
continue;
}
_xLen = ((localStorage[_x].length + _x.length) * 2);
_lsTotal += _xLen;
console.log(_x.substr(0, 50) + " = " + (_xLen / 1024).toFixed(2) + " KB")
};
console.log("Total = " + (_lsTotal / 1024).toFixed(2) + " KB");

or add this text in the field 'location' of a bookmark for convenient usage

javascript: var x, xLen, log=[],total=0;for (x in localStorage){if(!localStorage.hasOwnProperty(x)){continue;} xLen =  ((localStorage[x].length * 2 + x.length * 2)/1024); log.push(x.substr(0,30) + " = " +  xLen.toFixed(2) + " KB"); total+= xLen}; if (total > 1024){log.unshift("Total = " + (total/1024).toFixed(2)+ " MB");}else{log.unshift("Total = " + total.toFixed(2)+ " KB");}; alert(log.join("\n")); 

P.S. Snippets are updated according to request in the comment. Now the calculation includes the length of the key itself.
Each length is multiplied by 2 because the char in javascript stores as UTF-16 (occupies 2 bytes)

P.P.S. Should work both in Chrome and Firefox.

Calculating usage of localStorage space

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

  • DOMException:

    • code: 22
    • message: "Failed to execute 'setItem' on 'Storage': Setting the value of 'data' exceeded the quota."
    • name: "QuotaExceededError"

Mozilla Firefox

  • DOMException:

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

Safari

  • DOMException:

    • code: 22
    • message: "QuotaExceededError: DOM Exception 22"
    • name: "QuotaExceededError"

Internet Explorer, Edge (community)

  • DOMException:

    • code: 22
    • message: "QuotaExceededError"
    • name: "QuotaExceededError"

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.

What is the max size of localStorage values?

Quoting from the Wikipedia article on Web Storage:

Web storage can be viewed simplistically as an improvement on cookies, providing much greater storage capacity (10 MB per origin in Google Chrome(https://plus.google.com/u/0/+FrancoisBeaufort/posts/S5Q9HqDB8bh), Mozilla Firefox, and Opera; 10 MB per storage area in Internet Explorer) and better programmatic interfaces.

And also quoting from a John Resig article [posted January 2007]:

Storage Space

It is implied that, with DOM Storage,
you have considerably more storage
space than the typical user agent
limitations imposed upon Cookies.
However, the amount that is provided
is not defined in the specification,
nor is it meaningfully broadcast by
the user agent.

If you look at the Mozilla source code
we can see that 5120KB is the default
storage size for an entire domain.
This gives you considerably more space
to work with than a typical 2KB
cookie.

However, the size of this storage area
can be customized by the user
(so a
5MB storage area is not guaranteed,
nor is it implied) and the user agent
(Opera, for example, may only provide
3MB - but only time will tell.)

How to get total html5 storage size used by current application

No, not cross browser. IE sort of has it, the others don't. But of course, remaining size left on the domain can be calculated. See below examples.

For IE only:

var remSpace = window.localStorage.remainingSpace;

For FF/Chrome/Safari:

 var limit = 1024 * 1024 * 5; // 5 MB
var remSpace = limit - unescape(encodeURIComponent(JSON.stringify(localStorage))).length;

Opera:
5 MB is standard but the browser offers to increase limit as applications require more space.

How do you get the array length of a variable in a localStorage

You have to parse the array using JSON.parse and then you can get its length just like any other array.

var arrayFromStroage = JSON.parse(localStorage.getItem("name"));
var arrayLength = arrayFromStroage.length;

Just for your awareness, localStorage.getItem("name").length; will get you the length of JSON string that you have stored in localStorage. For array ["Gio","Ben"], its JSON string is "["Gio","Ben"]". So the length would be 13.

How to Check that how much offline storage has been Used

You could use localStorage.length to get the count of elements in the storage. But it is unlikely that it will directly give away the size (in bytes) of how much storage is used - unless you are storing monotonic data that lets you predict the size based on the count of keys.

But you do get a QUOTA_EXCEEDED_ERR exception when setting values if you do exceed the available limit. So, just wrap your code in a try..catch and if you do get error.type as QUOTA_EXCEEDED_ERR, then you could clear the space.

You could also iterate over all items in the storage to get its full size. But I would not do that given that it might take a bit of time as the storage increases. In case you are interested, something like this would work:

var size = 0;

for (var i = 0, len = localStorage.length; i < len; ++i) {
size += localStorage.getItem(localStorage.key(i)).length;
}

console.log("Size: " + size);

Ref: What happens when localStorage is full?

PS: I tried to get the size by iterating over the localStorage keys, and adding the size, but the browser tab crashed. So I'd say relying on the QUOTA_EXCEEDED_ERR is better.

UPDATE

You could also get a rough estimate of size using JSON.stringify(localStorage).length. Which seems faster than iterating over the keys, and doesn't crash the browser. But keep in mind that it contains additional JSON characters (such as {,},, and ") as browser would use them to wrap the keys and values. So the size would be slightly higher than the actual value.

HTML5 LocalStorage size

Regarding Firefox, quoting fron a John Resig article (posted January 2007)::

Storage Space

It is implied that, with DOM Storage, you have considerably more storage space than the typical user agent limitations imposed upon Cookies. However, the amount that is provided is not defined in the specification, nor is it meaningfully broadcast by the user agent.

If you look at the Mozilla source code we can see that 5120KB is the default storage size for an entire domain. This gives you considerably more space to work with than a typical 2KB cookie.

I guess it's the same for all the other browsers, but the default size can vary. For example, in Internet Explorer 8, the default is around 10Mb. Quoting from the MSDN article on DOM Storage:

window.localStorage

The localStorage attribute provides persistent storage areas for domains. It allows Web applications to store nearly 10 MB of user data, such as entire documents or a user's mailbox, on the client for performance reasons.

HTML5 LocalStorage: How Much Space Do I Have Left?

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.



Related Topics



Leave a reply



Submit