You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Chrome扩展移除特定Cookie异常:删除后重载页面值未更新求助

Hey there! Let's walk through what's causing your problem and fix it up so you can get fresh cookies after deletion and page reload.

Key Issues in Your Current Code

Let's break down the main problems holding you back:

  • Undefined url variable: Both cookieInfo and removeCookies reference a url variable that's never defined. You need to pull the current tab's URL directly from the tab object passed when the button is clicked.
  • Missing page reload logic: You mentioned needing to reload the site to get a new cookie, but your code doesn't actually trigger a page refresh after deleting cookies. Without reloading, the page keeps using old in-memory cookies.
  • Unmanaged async operations: Chrome's cookie API is asynchronous. Right now, you're calling cookieInfo and removeCookies back-to-back without waiting for deletion to finish, let alone waiting for the page to reload before checking for new cookies.
  • Incorrect cookie targeting: Using domain: url in chrome.cookies.getAll is wrong—domain expects just the domain (like example.com), not a full URL. Using the full tab URL directly is far more reliable.

Corrected Background.js Code

Here's the fixed version of your background script that addresses all these issues:

// Get the value of the specific cookie for a given URL
function cookieInfo(url, callback) {
  chrome.cookies.getAll({ url: url, name: "specificCookie" }, (cookies) => {
    const cookieValue = cookies.length > 0 ? cookies[0].value : "Cookie not found";
    console.log("Current cookie value:", cookieValue);
    if (callback) callback(cookieValue);
  });
}

// Remove all cookies for the given URL
function removeCookies(url, callback) {
  chrome.cookies.getAll({ url: url }, (cookies) => {
    console.log(`Found ${cookies.length} cookies to remove`);
    
    // Wrap each cookie deletion in a promise to track completion
    const deleteTasks = cookies.map(cookie => {
      return new Promise((resolve) => {
        const cookieUrl = `https${cookie.secure ? "s" : ""}://${cookie.domain}${cookie.path}`;
        chrome.cookies.remove({ url: cookieUrl, name: cookie.name }, resolve);
      });
    });

    // Wait for all cookies to be deleted before proceeding
    Promise.all(deleteTasks).then(() => {
      console.log("All cookies removed successfully");
      if (callback) callback();
    });
  });
}

// Handle browser action button click
chrome.browserAction.onClicked.addListener((tab) => {
  const currentPageUrl = tab.url;
  if (!currentPageUrl) return;

  // Step 1: Get the old cookie value
  cookieInfo(currentPageUrl, (oldCookieValue) => {
    console.log("Old cookie value before deletion:", oldCookieValue);

    // Step 2: Delete all cookies for the current page
    removeCookies(currentPageUrl, () => {
      // Step 3: Reload the current tab
      chrome.tabs.reload(tab.id, () => {
        // Step 4: Wait for the page to finish loading, then get the new cookie
        const tabLoadListener = (tabId, changeInfo) => {
          if (tabId === tab.id && changeInfo.status === "complete") {
            cookieInfo(currentPageUrl, (newCookieValue) => {
              console.log("New cookie value after reload:", newCookieValue);
            });
            // Clean up the listener so it doesn't fire on future tab updates
            chrome.tabs.onUpdated.removeListener(tabLoadListener);
          }
        };
        chrome.tabs.onUpdated.addListener(tabLoadListener);
      });
    });
  });
});

What Changed & Why

  • Defined currentPageUrl: Pulled directly from the tab object when the button is clicked, so all functions have the correct URL target.
  • Controlled async flow: Used promises and callbacks to ensure we follow the exact sequence you need:
    1. First capture the old cookie value
    2. Wait for all cookies to be deleted
    3. Reload the page to trigger new cookie generation
    4. Wait for the page to fully load before checking for the fresh cookie
  • Added page reload: chrome.tabs.reload forces the page to refresh, which makes the site generate new cookies instead of holding onto old ones.
  • Reliable deletion tracking: Used Promise.all to confirm all cookies are deleted before reloading, so we don't refresh the page too early.

Quick Note on Manifest Version

Keep in mind that Chrome is phasing out support for Manifest V2. For long-term compatibility, you should consider migrating your extension to Manifest V3. The core cookie/tab logic will be similar, but there are syntax changes (like replacing background.scripts with service_worker).

内容的提问来源于stack exchange,提问作者Michael

火山引擎 最新活动