Skip to content

Instantly share code, notes, and snippets.

@russmatney
Created November 18, 2025 15:55
Show Gist options
  • Select an option

  • Save russmatney/d329d7557a9f7f25431e8d61251e4499 to your computer and use it in GitHub Desktop.

Select an option

Save russmatney/d329d7557a9f7f25431e8d61251e4499 to your computer and use it in GitHub Desktop.
Fill local storage to test your app's behavior when it is full
// Fill localStorage to capacity using a single key for easy cleanup
const TEST_KEY = '__fill_test';
let currentData = '';
let chunkSize = 1024 * 1024; // Start with 1MB chunks
let totalSize = 0;
let iterations = 0;
console.log('Starting to fill localStorage...');
console.log(`Using key: ${TEST_KEY}`);
console.log('---');
// Function to generate a string of a specific size
function generateChunk(size) {
return 'x'.repeat(size);
}
// Try to fill localStorage incrementally
try {
while (true) {
try {
// Generate a chunk and append it to current data
const chunk = generateChunk(chunkSize);
currentData += chunk;
// Try to store it
localStorage.setItem(TEST_KEY, currentData);
totalSize += chunkSize;
iterations++;
// Log progress every 10 iterations or when we hit certain sizes
if (iterations % 10 === 0 || totalSize % (10 * 1024 * 1024) < chunkSize) {
console.log(`Added ${(totalSize / (1024 * 1024)).toFixed(2)} MB (${iterations} iterations)`);
}
} catch (e) {
// If we hit quota, try with smaller chunks
if (e.name === 'QuotaExceededError' || e.code === 22) {
if (chunkSize > 1) {
// Reduce chunk size and try again
chunkSize = Math.floor(chunkSize / 2);
console.log(`Quota exceeded. Reducing chunk size to ${(chunkSize / 1024).toFixed(2)} KB`);
// Remove the chunk we just tried to add
currentData = currentData.slice(0, -chunkSize * 2);
// Try one more time with the smaller chunk
continue;
} else {
// We're at 1 byte chunks and still hitting quota, we're done
throw e;
}
} else {
// Some other error
throw e;
}
}
}
} catch (e) {
if (e.name === 'QuotaExceededError' || e.code === 22) {
// Get the final size
const finalData = localStorage.getItem(TEST_KEY) || '';
const finalSize = new Blob([finalData]).size;
console.log('---');
console.log('localStorage is now full!');
console.log(`Final size: ${finalSize} bytes`);
console.log(`Final size: ${(finalSize / 1024).toFixed(2)} KB`);
console.log(`Final size: ${(finalSize / (1024 * 1024)).toFixed(2)} MB`);
console.log(`Total iterations: ${iterations}`);
console.log('---');
console.log('CLEANUP INSTRUCTIONS:');
console.log('To remove the test data, run the following in the console:');
console.log(`localStorage.removeItem('${TEST_KEY}');`);
console.log('---');
} else {
console.error('Unexpected error:', e);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment