-
-
Save russmatney/08343bcbb421b19414f79ec4f625c1cb to your computer and use it in GitHub Desktop.
Calculate used localStorage size for a website
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
| let entries = []; | |
| let totalSize = 0; | |
| // Collect all localStorage entries with their sizes | |
| for (let key in localStorage) { | |
| if (localStorage.hasOwnProperty(key)) { | |
| let keySize = new Blob([key]).size; // Size of the key | |
| let valueSize = new Blob([localStorage[key]]).size; // Size of the value | |
| let totalEntrySize = keySize + valueSize; | |
| totalSize += totalEntrySize; | |
| entries.push({ | |
| key: key, | |
| keySize: keySize, | |
| valueSize: valueSize, | |
| totalSize: totalEntrySize | |
| }); | |
| } | |
| } | |
| // Sort entries by total size (largest first) | |
| entries.sort((a, b) => b.totalSize - a.totalSize); | |
| // Prepare data for table display with formatted sizes | |
| let tableData = entries.map(entry => ({ | |
| Key: entry.key, | |
| 'Total Size (MB)': (entry.totalSize / (1024 * 1024)).toFixed(2), | |
| 'Total Size (KB)': (entry.totalSize / 1024).toFixed(2), | |
| 'Total Size (bytes)': entry.totalSize | |
| })); | |
| // Print entries in table format | |
| console.log('localStorage entries sorted by size (largest first):'); | |
| console.table(tableData); | |
| // Print total summary | |
| console.log('---'); | |
| console.log(`Total localStorage size: ${totalSize} bytes`); | |
| console.log(`Total size in KB: ${(totalSize / 1024).toFixed(2)} KB`); | |
| console.log(`Total size in MB: ${(totalSize / (1024 * 1024)).toFixed(2)} MB`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment