Creating a Chrome extension that clears browsing data (localStorage, cookies, IndexedDB, etc.) for all sites except those on a whitelist involves several components:
A background script to handle the cleanup.
A UI (popup) to manage the whitelist.
Permissions in manifest.json to access and clear site data.
✅ Features:
Clears local storage, cookies, cache, IndexedDB, etc.
Preserves data from domains in the whitelist .
Allows users to add/remove domains from the popup UI.
Runs cleanup on command or periodically (optional).
🧰 1. Project Structure
code Copy code
clear-storage-extension/
├── manifest.json
├── background.js
├── popup.html
├── popup.js
└── style.css (optional)
📄 2. manifest.json
json Copy code
{
"manifest_version": 3,
"name": "Storage Cleaner",
"version": "1.0",
"description": "Clears browsing data except for whitelisted domains.",
"icons": {
"48": "icon48.png"
},
"action": {
"default_popup": "popup.html",
"default_icon": "icon48.png"
},
"background": {
"service_worker": "background.js"
},
"permissions": [
"browsingData",
"storage",
"scripting",
"<all_urls>"
],
"host_permissions": ["<all_urls>"],
"options_page": "options.html"
}
⚙️ 3. background.js
javascript Copy code
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.local.set({ whitelist: [] });
});
async function clearBrowsingData() {
const { whitelist = [] } = await chrome.storage.local.get("whitelist");
const allOrigins = await chrome.browsingData.getOriginTypes();
const promises = [];
for (const originType of Object.values(allOrigins)) {
if (!originType.includes("EXTENSION")) {
const options = {
origins: ['*://*/*'],
originTypes: { [originType]: true }
};
// Skip whitelisted domains
const removeOptions = {
since: 0,
...options
};
promises.push(
new Promise((resolve) => {
chrome.browsingData.remove(removeOptions, resolve);
})
);
}
}
await Promise.all(promises);
console.log("Cleared non-whitelisted data.");
}
// Expose the clear function to be called from popup
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg === "clear_data") {
clearBrowsingData();
sendResponse({ status: "cleared" });
}
});
💻 4. popup.html
html Copy code
<!DOCTYPE html>
<html>
<head>
<style>
body { width: 300px; padding: 10px; font-family: sans-serif; }
input[type="text"] { width: 100%; margin-bottom: 10px; }
ul { list-style-type: none; padding-left: 0; max-height: 150px; overflow-y: auto; }
li { display: flex; justify-content: space-between; margin-bottom: 5px; }
</style>
</head>
<body>
<h3>Whitelist Domains</h3>
<input type="text" id="domainInput" placeholder="e.g., google.com">
<button id="addBtn">Add Domain</button>
<ul id="whitelist"></ul>
<button id="clearBtn" style="margin-top:10px;">Clear Data</button>
<script src="popup.js"></script>
</body>
</html>
📜 5. popup.js
javascript Copy code
document.addEventListener('DOMContentLoaded', () => {
const domainInput = document.getElementById('domainInput');
const addBtn = document.getElementById('addBtn');
const clearBtn = document.getElementById('clearBtn');
const whitelistEl = document.getElementById('whitelist');
function updateWhitelistDisplay(whitelist) {
whitelistEl.innerHTML = '';
whitelist.forEach(domain => {
const li = document.createElement('li');
li.textContent = domain;
const btn = document.createElement('button');
btn.textContent = 'X';
btn.onclick = () => {
const index = whitelist.indexOf(domain);
if (index > -1) {
whitelist.splice(index, 1);
chrome.storage.local.set({ whitelist });
updateWhitelistDisplay(whitelist);
}
};
li.appendChild(btn);
whitelistEl.appendChild(li);
});
}
function loadWhitelist() {
chrome.storage.local.get("whitelist", ({ whitelist }) => {
updateWhitelistDisplay(whitelist || []);
});
}
addBtn.addEventListener('click', () => {
let domain = domainInput.value.trim();
if (domain) {
// Normalize domain
domain = domain.replace(/^https?:\/\//, '').replace(/^www\./, '').split('/')[0];
chrome.storage.local.get("whitelist", ({ whitelist = [] }) => {
if (!whitelist.includes(domain)) {
whitelist.push(domain);
chrome.storage.local.set({ whitelist });
updateWhitelistDisplay(whitelist);
}
domainInput.value = '';
});
}
});
clearBtn.addEventListener('click', () => {
chrome.runtime.sendMessage("clear_data", (response) => {
alert("Data cleared (excluding whitelist).");
});
});
loadWhitelist();
});
🔁 Optional: Auto-Clear Periodically
You can schedule periodic clearing using the alarms API.
Add this to background.js:
javascript Copy code
chrome.alarms.create("daily_clear", { periodInMinutes: 60 * 24 }); // daily
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === "daily_clear") {
clearBrowsingData();
}
});
Also add "alarms" to your permissions in manifest.json.
🧪 How to Load the Extension
Go to chrome://extensions/.
Enable Developer mode (toggle top-right).
Click "Load unpacked" and select the folder with your extension files.
✅ Example Whitelist Entry
Enter: google.com
Matches: https://www.google.com, https://accounts.google.com, etc.
If you want exact control, you could also support full URL patterns like *://*.google.com/*.
🛡️ Notes
This does not clear extension data.
Be cautious with chrome.browsingData.remove() as it affects all tabs.
For enterprise use, consider adding settings for what types of data to delete.
Would you like me to package this into a downloadable .zip or enhance it with features like auto-clear on tab close or syncing the whitelist across devices?