Skip to content

Instantly share code, notes, and snippets.

@niksumeiko
Last active December 24, 2015 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niksumeiko/6823837 to your computer and use it in GitHub Desktop.
Save niksumeiko/6823837 to your computer and use it in GitHub Desktop.
JavaScript function that calculates allocated localStorage memory. Also applicable to get sessionStorage used memory.
/**
* Returns localStorage (or its particular key) allocated memory
* in Megabytes (MB).
* @param {string=} opt_key inside the storage to calculate
* used space for.
* @return {number} with 2 decimal points.
*/
function getLocalStorageUsedSpace(opt_key) {
var allocatedMemory = 0,
// It's also possible to get window.sessionStorage.
STORAGE = window.localStorage,
key;
if (!STORAGE) {
// Web storage is not supported by the browser,
// returning 0, therefore.
return allocatedMemory;
}
for (key in STORAGE) {
if (STORAGE.hasOwnProperty(key) && (!opt_key || opt_key === key)) {
allocatedMemory += (STORAGE[key].length * 2) / 1024 / 1024;
}
}
return parseFloat(allocatedMemory.toFixed(2));
}
// Examples:
// Logging how much memory localStorage is using.
console.log( getLocalStorageUsedSpace() + 'MB' );
// Logging how much memory particular key inside the localStorage is using.
console.log( getLocalStorageUsedSpace('YOUR_KEY_NAME') + 'MB' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment