Last active
December 24, 2015 15:49
-
-
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.
This file contains hidden or 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 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