Skip to content

Instantly share code, notes, and snippets.

@tkambler
Last active April 22, 2024 19:23
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);
};
@amineshon
Copy link

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