-
-
Save tkambler/71050d80f1a57ea83c18 to your computer and use it in GitHub Desktop.
| /** | |
| * 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");
Hi, came across this discussion and decided to add my input
Object.keys(localStorage).map(k => (localStorage.getItem(k) ?? '').length * 2 / 1024 / 1024).reduce((a, b) => a + b);
a one-liner
See also navigator.storage.estimate() https://developer.mozilla.org/en-US/docs/Web/API/StorageManager/estimate
I had 2 little bugs:
NaNamountfor ... inalso takes stuff in the prototype oflocalStorageobject (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 ❤️.