Clear Cache Memory Using JavaScript Examples
In this article
Clearing cache memory using JavaScript typically refers to managing browser caches such as the Cache API or localStorage/sessionStorage. While JavaScript cannot directly clear the browser's entire cache (like images or stylesheets cached by default), it can programmatically manage caches it controls, especially those created via the Cache API in service workers or clear data stored in localStorage and sessionStorage. This is useful for debugging, forcing updates in progressive web apps (PWAs), or managing user data. This guide covers how to clear specific caches using JavaScript, with practical examples and best practices.
What You'll Need
- A modern web browser (Chrome, Firefox, Edge, Safari) that supports JavaScript and the Cache API
- Basic knowledge of JavaScript and browser developer tools
- A website or web app where you have control over JavaScript execution (e.g., your own site or a test environment)
- Access to the browser’s console (F12 or right-click → Inspect)
Step-by-Step
- Open browser developer tools: Press F12 or right-click on the page and select "Inspect" to open developer tools. Navigate to the "Console" tab.
- Check if Cache API is supported: Run
if ('caches' in window) { console.log('Cache API supported'); }in the console. If it logs the message, your browser supports the Cache API. - List all cache names: To see what caches exist, run:
This returns an array of cache names created by your site’s service workers.async function listCaches() { const cacheNames = await caches.keys(); console.log('Caches:', cacheNames); } listCaches(); - Delete a specific cache: Use
caches.delete(cacheName)to remove a named cache. For example:
This permanently removes the specified cache and all its stored responses.async function clearSpecificCache(name) { const isDeleted = await caches.delete(name); console.log(`Cache ${name} deleted:`, isDeleted); } // Replace 'my-cache' with actual cache name clearSpecificCache('my-cache'); - Clear all caches: To delete all caches associated with your origin:
This loops through all cache names and deletes each one.async function clearAllCaches() { const cacheNames = await caches.keys(); const deletions = cacheNames.map(name => caches.delete(name)); await Promise.all(deletions); console.log('All caches cleared'); } clearAllCaches(); - Clear localStorage and sessionStorage: These are separate from the Cache API but often confused. To clear them:
Or clear specific items with// Clear localStorage localStorage.clear(); // Clear sessionStorage sessionStorage.clear();localStorage.removeItem('key'). - Verify cache is cleared: Re-run the
listCaches()function or check Application/Storage tab in developer tools to confirm caches are gone.
Common Mistakes
- Assuming JavaScript clears the entire browser cache: It only clears caches created via the Cache API or storage APIs, not browser-wide HTTP cache.
- Not using
async/awaitor handling promises: Cache operations are asynchronous. Forgetting toawaitor chain.then()leads to errors or silent failures. - Hardcoding cache names without checking first: Cache names can change. Always list caches first or use dynamic naming strategies.
- Clearing caches in production unintentionally: Running clear scripts in live environments can break offline functionality. Always test in development first.
- Mixing up Cache API with localStorage: These are different storage mechanisms. Use the correct method for the correct type.
Tips
- Use versioned cache names: Name caches like
my-app-cache-v1to make clearing or updating easier during app updates. - Log cache operations: Always log success or failure to confirm actions, especially in service workers.
- Clear caches during service worker updates: In your service worker file, use the
activateevent to clear old caches:
This ensures old caches don't clutter the user's device.self.addEventListener('activate', event => { event.waitUntil( caches.keys().then(cacheNames => Promise.all( cacheNames .filter(name => !['current-cache'].includes(name)) .map(name => caches.delete(name)) ) ) ); }); - Test in private/incognito mode: This avoids interference from existing cached data during development.
- Use developer tools for inspection: The Application tab in Chrome DevTools lets you view and manually clear caches, useful for debugging.
Troubleshooting
- No caches appear when listing: Your site may not be using the Cache API. Check if a service worker is registered with
navigator.serviceWorker.controller. - Cache deletion returns false: The cache name may be incorrect or already deleted. Double-check spelling and re-list caches.
- Permission denied or security error: You can only access caches from the same origin. Ensure you're on the correct domain and using HTTPS (required for service workers in most browsers).
- Changes not taking effect: Hard refresh (Ctrl+F5 or Cmd+Shift+R) or clear browser cache manually via settings if HTTP cache is interfering.
- Script runs but nothing happens: Ensure you're awaiting asynchronous operations. Wrap calls in
asyncfunctions or use.then(). - Service worker still serves old content: After clearing caches, unregister the service worker and reload:
navigator.serviceWorker.getRegistrations().then(regs => regs.forEach(r => r.unregister())).