Delete cookies chrome extension

2020-05-18 04:34发布

问题:

I want to delete all cookie on certain domain automatically so I have crafted an extension.I am able to view the cookies for the domain but I didn't find any method to delete them

Here is my code the function eraseCookie is just called one time

Any suggestions ?

function eraseCookie(name) {
    document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

$(document).ready(function() {


var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
{
  window.alert(cookies[i]);
  eraseCookie(cookies[i].split("=")[0]);
}

});

I am also using jquery but I don't see a problem in that!

    {
        "name": "Gapa",
        "version": "0.1",
        "description": "",
        "browser_action":   {
            "default_icon": "sigla.png",
            "default_title": "",
            "popup": "hello.html"
        },
        "content_scripts": [
        {
          "matches": ["*://*.google.ro/*"],
          "js": ["jquery-1.8.2.min.js","cookie_handler.js"]
        }
      ],
       "icons": {
          "128":"sigla.png" },
       "permissions": [
        "cookies",
        "tabs",
        "*://*.google.ro/*"
      ],
      "manifest_version": 2


    }

LE : Here is how my script file looks now:

$(document).ready(function() {

var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++)
{
  chrome.cookies.remove({"url": ".google.ro", "name":cookies[i].split("=")[0]}, function(deleted_cookie) { window.alert('deleted cookie') });
}

});

回答1:

First of all you must provide cookies permission in your manifest.

Second of all Chrome provides you with cookies api where remove function is localted:

chrome.cookies.remove(object details, function callback);

You can use it like that:

chrome.cookies.remove({"url": "http://domain.com", "name": "cookieName"}, function(deleted_cookie) { console.log(deleted_cookie); });

Try using this to list all cookies for selected domains (inner delete function removes all cookies from this domain):

chrome.cookies.getAll({domain: "domain.com"}, function(cookies) {
    for(var i=0; i<cookies.length;i++) {
        chrome.cookies.remove({url: "http://domain.com" + cookies[i].path, name: cookies[i].name});
    }
});

In your manifest.json add:

  "background": {
    "scripts": ["background.js"]
  },

and in background.js you include proposed function.



回答2:

I pieced together Arkadiusz's answer and got this working:

In manifest.json:

"background": {
    "scripts": ["background.js"]
  },
"permissions": [
    "cookies",
    "https://*/",
    "http://*/"
  ]

In background.js:

chrome.cookies.getAll({domain: ".mydomain.com"}, function(cookies) {
    for(var i=0; i<cookies.length;i++) {
      console.log(cookies[i]);

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