为什么cookies没有被删除

问题描述 投票:0回答:1

我正在尝试遵循this答案,但它似乎对我不起作用。在对

https://https.api.pqr.com/folder/
的请求中,我可以看到所有 cookie 仍然存在。

这是代码:

    chrome.cookies.getAll({domain: ".pqr.com"}, async function(cookies) {
      for(var i = 0; i < cookies.length; i++) {
        try {
          console.log(cookies[i], "to remove");
          chrome.cookies.remove({url: "http://" + cookies[i].domain  + cookies[i].path, name: cookies[i].name});          
          console.log(cookies[i], "removed");
        } catch (ex) {
          console.log(cookies[i], ex);
        }
        try {
          console.log(cookies[i], "to remove");
          chrome.cookies.remove({url: "https://" + cookies[i].domain  + cookies[i].path, name: cookies[i].name});          
          console.log(cookies[i], "removed");
        } catch (ex) {
          console.log(cookies[i], ex);
        }
      }

      const resp = await fetch("https://https.api.pqr.com/folder/", {
        method: "POST",
        signal: params.signal,
        body: JSON.stringify({
          userInput: "someval,
        }),
        headers: {
          "Content-Type": "application/json;charset=UTF-8",
          "Accept-Language": "en-US,en;q=0.9",
          "Cookie": ''
        },
      });

    });
javascript google-chrome google-chrome-extension browser-addons
1个回答
0
投票

有一些潜在原因可能导致 Cookie 无法正确删除。让我们仔细研究一下并改进代码:

不正确的 Cookie 域或路径: 域和路径必须与设置 cookie 时使用的域和路径完全匹配。如果 cookies[i].domain 以点开头(例如 .pqr.com),则它可能无法与您正在构建的 url 一起正常工作。您应该确保传递给 chrome.cookies.remove 的 URL 与用于设置 cookie 的 URL 完全匹配。

chrome.cookies.remove({
  url: "https://" + cookies[i].domain.replace(/^\./, '') + cookies[i].path,
  name: cookies[i].name
});

chrome.cookies.remove 的异步性质: chrome.cookies.remove 函数是异步的。您在调用删除后立即记录“已删除”,但这并不意味着 cookie 已被删除。最好使用回调来确定 cookie 何时被删除:

chrome.cookies.remove({url: "https://" + cookies[i].domain + cookies[i].path, name: cookies[i].name}, function(removedCookie) {
  console.log(removedCookie, "removed");
});
© www.soinside.com 2019 - 2024. All rights reserved.