I am currently developing a site that will make use of HTML5's localStorage. I've read all about the size limitations for different browsers. However, I haven't seen anything on how to find out the current size of a localStorage instance. This question seems to indicate that JavaScript doesn't have a built in way of showing the size for a given variable. Does localStorage have a memory size property that I haven't seen? Is there an easy way to do this that I'm missing?
My site is meant to allow users to enter information in an 'offline' mode, so being able to give them a warning when the storage is almost full is very important.
As the spec goes, each character of a string is 16 bit.
But inspecting with chrome (Settings>Content Settings>Cookies & Site data) shows us that initiating localStorage takes 3kB (overhead size)
And stored data size follows this relation (accurate to 1kB)
3 + ((localStorage.x.length*16)/(8*1024)) kB
where localStorage.x is your storage string.
I would use the code of @tennisgen which get all and count the content, but I count the keys themselves:
You can get the current size of the local storage data using the Blob function. This may not work in old browsers.
Example:
Object.values() turns the localStorage object to an array. Blob turns the array into raw data.
Hope this help someone.
Because Jas- example on jsfiddle does not work for me I came up with this solution. (thanks to Serge Seletskyy and Shourav for their bits I used in the code below)
Below is the function that can be used to test how much space is available for localStorage and (if any keys are already in lS) how much space is left.
It is a little brute force but it works in almost every browser... apart from Firefox. Well in desktop FF it takes ages (4-5min) to complete, and on Android it just crashes.
Underneath the function is a short summary of tests that I have done in different browsers on different platforms. Enjoy!
And as promised above some test in different browsers:
GalaxyTab 10.1
iPhone 4s iOS 6.1.3
MacBook Pro OSX 1.8.3 (Core 2 Duo 2.66 8Gb memory)
iPad 3 iOS 6.1.3
Windows 7 -64b (Core 2 Duo 2.93 6Gb memory)
Win 8 (Under Parallels 8)
In addition to @serge's answer which is most voted here, size of the keys need to be considered. Code below will add the size of the keys stored in
localStorage