We can convert our browser’s local storage object into a blob to get the size of it.
To do this, we write:
const {
size
} = new Blob(Object.values(localStorage))
console.log(size)
We call Object.values
with localStorage
to get an array of values of our local storage.
Then we pass that into the Blob
constructor so that we can use the size
property of it to get the size.
Get the Size in Kilobytes
To get the size in kilobytes, we can write our own function to calculate the number of bytes stored in local storage and convert that to kilobytes.
For example, we can write:
const localStorageSpace = () => {
let allStrings = '';
for (const key of Object.keys(window.localStorage)) {
allStrings += window.localStorage\[key\];
}
return allStrings ? 3 + ((allStrings.length \* 16) / (8 \* 1024)) + ' KB' : 'Empty (0 KB)';
};
console.log(localStorageSpace())
We define the localStorageSpace
function that concatenates all the strings together into the allStrings
string.
Then we calculate the size of it by getting the length
of it, multiply by 16.
And then we divide it by 8 * 1024
to convert it into kilobytes.
Finally, we add 3 to it.