Last active
April 22, 2024 19:23
-
-
Save tkambler/71050d80f1a57ea83c18 to your computer and use it in GitHub Desktop.
Calculate size of used LocalStorage space
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Returns the total amount of disk space used (in MB) by localStorage for the current domain. | |
*/ | |
var getLocalStorageSize = function() { | |
var total = 0; | |
for (var x in localStorage) { | |
// Value is multiplied by 2 due to data being stored in `utf-16` format, which requires twice the space. | |
var amount = (localStorage[x].length * 2) / 1024 / 1024; | |
total += amount; | |
} | |
return total.toFixed(2); | |
}; |
thanks
the capacity of local storage in Chrome is up to 10Mb right?
Not working for me > "0.00"
.
This one does work well tho: https://stackoverflow.com/a/15720835/8816585
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 above was great but I needed it as a function and I only need the Total size.
This one seems better
let localStorageSize = function () {
let _lsTotal = 0,_xLen, _x;
for (_x in localStorage) {
if (!localStorage.hasOwnProperty(_x)) continue;
_xLen = (localStorage[_x].length + _x.length) * 2;
_lsTotal += _xLen;
}
return (_lsTotal / 1024).toFixed(2);
}
you can use it like this
console.log( `size: ${localStorageSize()}kb`)
response
size: 3.63kb
thanks ❤
function calculateTotalLocalStorageUsage() {
let total = 0;
for (let key in localStorage) {
let value = localStorage.getItem(key);
total += (new TextEncoder().encode(value)).length;
}
let inKB = (total / 1024);
return inKB.toFixed(2);
}
// Log the total localStorage usage
console.log("Total localStorage usage: " + calculateTotalLocalStorageUsage() + " kb");
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I had 2 little bugs:
NaN
amountfor ... in
also takes stuff in the prototype oflocalStorage
object (like getItem function, length property, ... but the impact is really slow)I had to add a little condition to fix that:
but thank you very much for this ❤️.