Skip to content

Instantly share code, notes, and snippets.

@tkambler
Last active June 14, 2024 18:25
Show Gist options
  • Save tkambler/71050d80f1a57ea83c18 to your computer and use it in GitHub Desktop.
Save tkambler/71050d80f1a57ea83c18 to your computer and use it in GitHub Desktop.
Calculate size of used LocalStorage space
/**
* 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);
};
@Kolostov
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment