Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash-preview-04-17· GoogleHugging Face LMArena Human Preference 140K

write a chrome extension to clear storage (local storage, cookies, indexdb, etc) for all…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwen3-235b-a22b-no-thinking’s answer.
  1. User

    write a chrome extension to clear storage (local storage, cookies, indexdb, etc) for all sites except those in a given whitelist

  2. Gemini Assistant

    Okay, here's a Chrome extension that allows you to define a whitelist of domains and clear cookies for all sites except those on the list.

    Important Considerations & Limitations:

    1. API Limitations: Chrome's standard chrome.browsingData.remove API is designed for bulk clearing data types (cookies, local storage, cache, history, etc.) based on a time range. It does not have a built-in mechanism to exclude specific origins (domains) for cookies, local storage, or IndexedDB when performing a bulk clear.
    2. Selective Clearing: Clearing data selectively per origin is possible for cookies using chrome.cookies.getAll() and chrome.cookies.remove(). However, there isn't a standard API to easily get a list of all origins that have data in Local Storage or IndexedDB across the entire browser profile, making selective clearing of those types difficult or impossible with standard methods.
    3. Scope of this Extension: Given the above, this extension will focus on implementing the whitelist logic specifically for cookies, as this is feasible. It will include the UI to save the whitelist and a button to trigger clearing only cookies for non-whitelisted sites. It will include a note about the limitations for other storage types.

    Extension Files:

    1. manifest.json
    2. popup.html
    3. popup.js
    4. background.js
    5. (Optional) Icons: icons/icon16.png, icons/icon48.png, icons/icon128.png

    Step-by-Step Implementation:

    1. manifest.json

    This file tells Chrome about your extension.

    {
      "manifest_version": 3,
      "name": "Selective Cookie Cleaner",
      "version": "1.0",
      "description": "Clear cookies for all sites except those in a whitelist.",
      "permissions": [
        "cookies",
        "storage"
      ],
      "action": {
        "default_popup": "popup.html",
        "default_icon": {
          "16": "icons/icon16.png",
          "48": "icons/icon48.png",
          "128": "icons/icon128.png"
        }
      },
      "icons": {
        "16": "icons/icon16.png",
        "48": "icons/icon48.png",
        "128": "icons/icon128.png"
      },
      "background": {
        "service_worker": "background.js"
      }
    }
    
    • manifest_version: Set to 3 for current Chrome extensions.
    • name, version, description: Basic info.
    • permissions:
      • "cookies": Required to access and remove browser cookies.
      • "storage": Required to save and load the whitelist using chrome.storage.local.
    • action: Defines the browser action button (the icon next to the address bar).
      • default_popup: Specifies the HTML file to show when the icon is clicked.
      • default_icon: Paths to your extension icons in different sizes. Create a folder named icons and put your image files there (replace with your own or use placeholders).
    • background: Specifies the service worker script that runs in the background.

    2. popup.html

    This is the HTML for the small window that appears when you click the extension icon.

    <!DOCTYPE html>
    <html>
    <head>
      <title>Selective Cookie Cleaner</title>
      <style>
        body { font-family: sans-serif; padding: 10px; min-width: 300px; }
        h2 { margin-top: 0; }
        textarea { width: 95%; height: 100px; margin-bottom: 10px; padding: 5px; }
        button { margin-right: 10px; padding: 8px 15px; cursor: pointer; }
        button:hover { opacity: 0.9; }
        #status { margin-top: 15px; font-weight: bold; }
        .success { color: green; }
        .error { color: red; }
        .info { color: gray; font-size: 0.9em; margin-top: 10px; }
        hr { margin: 15px 0; }
      </style>
    </head>
    <body>
      <h2>Whitelist Domains</h2>
      <p class="info">Enter domains (e.g., google.com, example.org) one per line. Cookies for these sites and their subdomains will be kept.</p>
      <textarea id="whitelistInput"></textarea>
      <button id="saveWhitelist">Save Whitelist</button>
    
      <hr>
    
      <h2>Clear Cookies</h2>
       <p class="info">This will remove all cookies except those belonging to the whitelisted domains.</p>
      <p class="info error">Note: Due to Chrome API limitations, only <strong>cookies</strong> can be selectively cleared this way. Local Storage, IndexedDB, Cache, etc., cannot be excluded by domain using standard methods. Clearing these globally would remove data for *all* sites.</p>
      <button id="clearCookies">Clear Cookies (Except Whitelist)</button>
    
      <div id="status"></div>
    
      <script src="popup.js"></script>
    </body>
    </html>
    
    • Basic HTML structure.
    • Includes a textarea for entering the whitelist domains.
    • Includes buttons to "Save Whitelist" and "Clear Cookies".
    • Includes a div for displaying status messages.
    • Includes a script tag to load popup.js.
    • Added a clear note about the limitation regarding other storage types.

    3. popup.js

    This script runs when the popup is opened. It handles loading/saving the whitelist from storage and sending a message to the background script to clear cookies.

    document.addEventListener('DOMContentLoaded', function() {
      const whitelistInput = document.getElementById('whitelistInput');
      const saveButton = document.getElementById('saveWhitelist');
      const clearCookiesButton = document.getElementById('clearCookies');
      const statusDiv = document.getElementById('status');
    
      // Load saved whitelist on popup open
      chrome.storage.local.get('whitelist', function(data) {
        if (data.whitelist && Array.isArray(data.whitelist)) {
          whitelistInput.value = data.whitelist.join('\n');
          console.log('Loaded whitelist:', data.whitelist);
        } else {
            console.log('No whitelist found or invalid format.');
        }
      });
    
      // Save whitelist button listener
      saveButton.addEventListener('click', function() {
        const whitelist = whitelistInput.value
          .split('\n') // Split by line breaks
          .map(line => line.trim()) // Trim whitespace
          .filter(line => line.length > 0); // Remove empty lines
    
        chrome.storage.local.set({ whitelist: whitelist }, function() {
          if (chrome.runtime.lastError) {
              statusDiv.textContent = 'Error saving whitelist: ' + chrome.runtime.lastError.message;
              statusDiv.className = 'error';
              console.error('Error saving whitelist:', chrome.runtime.lastError);
          } else {
              statusDiv.textContent = 'Whitelist saved!';
              statusDiv.className = 'success';
              console.log('Whitelist saved:', whitelist);
          }
          setTimeout(() => { statusDiv.textContent = ''; statusDiv.className = ''; }, 3000); // Clear status after 3 seconds
        });
      });
    
      // Clear Cookies button listener
      clearCookiesButton.addEventListener('click', function() {
        statusDiv.textContent = 'Clearing cookies...';
        statusDiv.className = ''; // Clear previous status class
    
        // Send message to the background script to perform the clear operation
        chrome.runtime.sendMessage({ action: "clearCookies" }, function(response) {
          if (chrome.runtime.lastError) {
              statusDiv.textContent = 'Error communicating with background script: ' + chrome.runtime.lastError.message;
              statusDiv.className = 'error';
               console.error('Error sending message:', chrome.runtime.lastError);
               return; // Stop execution if message failed
          }
    
          if (response && response.status === 'success') {
            statusDiv.textContent = `Cleared cookies for ${response.removedCount} distinct sites.`;
            statusDiv.className = 'success';
            console.log('Cookie clearing successful, response:', response);
          } else {
             statusDiv.textContent = `Error clearing cookies: ${response ? response.error : 'Unknown error'}`;
             statusDiv.className = 'error';
             console.error('Cookie clearing failed:', response);
          }
           // Clear status after a longer delay for clearing results
           setTimeout(() => { statusDiv.textContent = ''; statusDiv.className = ''; }, 5000);
        });
      });
    });
    
    • Listens for the DOM to be fully loaded.
    • Retrieves elements from popup.html.
    • When the popup opens, it loads the saved whitelist from chrome.storage.local and puts it in the textarea.
    • Adds an event listener to the "Save Whitelist" button: reads the textarea, splits it into lines, trims whitespace, filters empty lines, and saves the resulting array to chrome.storage.local.
    • Adds an event listener to the "Clear Cookies" button: sends a message to the background script (background.js) asking it to perform the cookie clearing. It waits for a response from the background script and updates the status div.

    4. background.js

    This script runs in the background and contains the core logic for clearing cookies based on the whitelist. Service workers are event-driven.

    // Listener for messages from popup.js (or other parts of the extension)
    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
      // Check if the message is the "clearCookies" action
      if (request.action === "clearCookies") {
        console.log("Received clearCookies action");
        // Perform the async operation and handle the promise
        clearCookiesExceptWhitelisted()
          .then((removedCount) => {
             // Send a success response back to the sender (popup.js)
             sendResponse({ status: "success", removedCount: removedCount });
             console.log(`Sent success response: cleared ${removedCount} sites.`);
          })
          .catch(error => {
             // Send an error response back
             console.error("Error during clearCookiesExceptWhitelisted:", error);
             sendResponse({ status: "error", error: error.message });
          });
    
        // Return true to indicate that you will send a response asynchronously
        return true;
      }
    });
    
    // Async function to clear cookies
    async function clearCookiesExceptWhitelisted() {
      console.log("Starting cookie clearing process...");
    
      // 1. Get the whitelist from storage
      const data = await chrome.storage.local.get('whitelist');
      // Ensure whitelist is an array, default to empty array if not found or invalid
      const whitelist = Array.isArray(data.whitelist) ? data.whitelist.map(domain => domain.toLowerCase().trim()).filter(d => d.length > 0) : [];
      console.log("Active Whitelist:", whitelist);
    
      if (whitelist.length === 0) {
          console.warn("Whitelist is empty. No cookies will be removed.");
          // Optionally clear all if whitelist is empty? Let's not, safer.
          return 0; // Return 0 removed count
      }
    
    
      // 2. Get all cookies
      // The {} means get all cookies regardless of URL, domain, path etc.
      const allCookies = await chrome.cookies.getAll({});
      console.log(`Found ${allCookies.length} total cookies.`);
    
      let removedDomainsCount = 0;
      const processedDomains = new Set(); // To count distinct domains from which cookies were removed
    
      // 3. Iterate through all cookies and remove if not whitelisted
      for (const cookie of allCookies) {
        // Determine the cookie domain for matching (handle leading dots)
        const cookieDomain = cookie.domain.startsWith('.') ? cookie.domain.substring(1).toLowerCase() : cookie.domain.toLowerCase();
    
        // Check if the cookie's domain matches any domain in the whitelist
        // A cookie domain 'mail.google.com' should match a whitelist entry 'google.com'
        // A cookie domain '.google.com' should match 'google.com' or '.google.com'
        const isWhitelisted = whitelist.some(whitelistedDomain => {
           // Direct match or subdomain match
           // whitelistedDomain must be a suffix of cookieDomain,
           // separated by a dot, or be an exact match.
           // Example: cookieDomain='mail.google.com', whitelistedDomain='google.com' -> 'mail.google.com'.endsWith('.google.com') is true
           // Example: cookieDomain='google.com', whitelistedDomain='google.com' -> 'google.com' === 'google.com' is true
           return cookieDomain === whitelistedDomain || cookieDomain.endsWith('.' + whitelistedDomain);
        });
    
        // 4. If the cookie is NOT whitelisted, remove it
        if (!isWhitelisted) {
          // Construct the URL required by chrome.cookies.remove
          // Use the original cookie domain and path, and derive scheme from 'secure' flag
          const protocol = cookie.secure ? "https://" : "http://";
          // chrome.cookies.remove expects the full URL the cookie is accessible from
          // For domain cookies, the path is usually '/', and the host is the domain.
          // It seems `remove` is lenient with the path and precise with domain/name/storeId.
          // A robust URL construction based on cookie properties:
          const url = protocol + cookie.domain + cookie.path;
    
          try {
             await chrome.cookies.remove({ url: url, name: cookie.name, storeId: cookie.storeId });
             // console.log(`Removed cookie: ${cookie.name} from ${cookie.domain}`); // Log removed cookies (optional)
             if (!processedDomains.has(cookieDomain)) {
                 processedDomains.add(cookieDomain);
                 removedDomainsCount++;
             }
          } catch (error) {
             console.error(`Failed to remove cookie ${cookie.name} from ${cookie.domain}:`, error);
          }
        }
        // else {
        //   console.log(`Kept cookie: ${cookie.name} from ${cookie.domain} (whitelisted)`); // Log kept cookies (optional)
        // }
      }
    
      console.log(`Finished cookie clearing. Removed cookies from ${removedDomainsCount} distinct domains.`);
      return removedDomainsCount; // Return the count of domains from which cookies were removed
    }
    
    • chrome.runtime.onMessage.addListener: This listens for messages sent from other parts of the extension (like popup.js). When it receives a message with action: "clearCookies", it calls clearCookiesExceptWhitelisted.
    • clearCookiesExceptWhitelisted:
      • Asynchronously gets the whitelist from chrome.storage.local.
      • Gets all cookies using chrome.cookies.getAll({}).
      • Loops through each cookie.
      • For each cookie, it checks if its domain matches any domain in the whitelist using a robust suffix check (handles subdomains and leading dots).
      • If the cookie's domain is not found in the whitelist, it constructs the necessary url (protocol + domain + path) and calls chrome.cookies.remove() to delete that specific cookie.
      • Counts the number of distinct domains from which cookies were removed and returns this count.
      • Uses async/await for cleaner asynchronous code.

    5. Icons (Optional but recommended)

    Create a folder named icons and add your extension icons in these sizes:

    • icon16.png (16x16 pixels)
    • icon48.png (48x48 pixels)
    • icon128.png (128x128 pixels) You can use simple colored squares or text for testing purposes.

    How to Install and Use:

    1. Save all the files (manifest.json, popup.html, popup.js, background.js, and the icons folder with images) into a single folder.
    2. Open Google Chrome.
    3. Go to the Extensions page (chrome://extensions/).
    4. Enable "Developer mode" using the toggle switch in the top right corner.
    5. Click the "Load unpacked" button in the top left corner.
    6. Select the folder where you saved the extension files.
    7. The extension should now appear in your extensions list, and its icon should be visible in the toolbar.
    8. Click the extension icon.
    9. Enter the domains you want to keep cookies for, one per line, in the text area (e.g., google.com, mybank.com).
    10. Click "Save Whitelist".
    11. Click "Clear Cookies (Except Whitelist)".
    12. Check the status message in the popup to see how many sites' cookies were cleared.
    13. Verify by visiting sites you expected cookies to be removed from (you should be logged out or settings reset if they rely on cookies) and sites you whitelisted (you should ideally remain logged in if you were before).

    This extension provides a practical way to manage cookies based on a whitelist, acknowledging the technical constraints of clearing other storage types selectively via standard Chrome APIs.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.