最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - chrome.cookies.getAll returns an empty array - Stack Overflow

programmeradmin2浏览0评论

I'm working on a simple chrome extension that will delete all cookies from a domain with one click but for some reason, it's not working. When I try to get all the cookies from the domain, it returns an empty array. What am I doing wrong? Here's the js script:

$("#fixTheCookiesButton").click(() => {
  // delete the cookies
  chrome.cookies.getAll({domain: ""}, (cookies) => {
    console.log("deleting " + cookies.length + " cookies")
    for(var i = 0; i < cookies.length; i++){
      console.log(i + " deleted")
      chrome.cookies.remove({
        url: "" + cookies[i].path,
        name: cookies[i].name
      })
    }
    
    // some other stuff that isn't relevant here
}

I'm working on a simple chrome extension that will delete all cookies from a domain with one click but for some reason, it's not working. When I try to get all the cookies from the domain, it returns an empty array. What am I doing wrong? Here's the js script:

$("#fixTheCookiesButton").click(() => {
  // delete the cookies
  chrome.cookies.getAll({domain: "https://www.youtube.com"}, (cookies) => {
    console.log("deleting " + cookies.length + " cookies")
    for(var i = 0; i < cookies.length; i++){
      console.log(i + " deleted")
      chrome.cookies.remove({
        url: "https://www.youtube.com" + cookies[i].path,
        name: cookies[i].name
      })
    }
    
    // some other stuff that isn't relevant here
}

and here's my manifest:

{
  "manifest_version": 2,
  "name": "FixYT",
  "version": "1.0",
  "description": "Fixes that YT cookie bug with one click",
  "browser_action": {
          "default_title": "FixYT",
          "default_popup": "popup.html"
  },
  "permissions": [
    "cookies",
    "https://www.youtube.com/",
    "*://www.youtube.com/",
    "tabs",
    "*://*/"
  ]
}

I've tried looking around the internet but I can't find any solutions to this.

Share Improve this question asked Jun 9, 2018 at 7:24 M. FarnikM. Farnik 2751 gold badge3 silver badges10 bronze badges 2
  • Remove https:// from getAll parameter because scheme/ protocol is not a part of the domain. – woxxom Commented Jun 9, 2018 at 7:52
  • use url instead of domain in getAll function reference – Vivek Commented Jun 9, 2018 at 8:21
Add a comment  | 

4 Answers 4

Reset to default 10

Both permissions and host_permissions are required.

"permissions": [
  "cookies",
  "tabs"
],
"host_permissions": ["<all_urls>"],

As isa says, chrome.cookies is only defined in background.js

Add to manifest so we have access to chrome.cookies in background.js  

 "permissions": [
      ...
       "cookies",
     ],

background.js

...
chrome.cookies.getAll({
    }, function (theCookies) {
        cookies = theCookies
        console.log(cookies)
    });


Sending Cookies from background.js to other views

(Not required, but still useful)


Add to panel.js to search for cookies. [This will fire when you open your extension ie (puzzle piece icon) -> click on your extension]

chrome.runtime.sendMessage({ command: "GetCookies"}, 
      function(response) {
            console.log("I received cookies!")
            console.log(response)
      }
);

Add to background.js logic to get cookies from the browser and check for known cookies


chrome.runtime.onMessage.addListener(function (message, sender, callback) {
    if (message.command === 'GetCookies') {
        checkKnownCookies()
    }
});
let cookies = [] // Hold IDs of recognized cookies
function checkKnownCookies() {
    chrome.cookies.getAll({
    }, function (theCookies) {
        cookies = theCookies
        console.log(cookies)
        callback(theCookies)
    });
}
 

https://developer.chrome.com/docs/extensions/reference/cookies/#method-getAll

To view console for background.js go to (puzzle piece icon) -> manage extensions and click on the href link to background.html for your extension

you should call this code block in background.js

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

This is a more modern example of passing cookies from a service worker to a content script which uses promises rather than callbacks as per current guidelines. You have to be using manifest version 3 or higher for this approach.

content_script.js

chrome.runtime.sendMessage({ action: 'getCookies', domain: document.domain })
    .then(response => {
        if (response.success) {
            // Construct the cookie header string
            const cookieHeader = response.cookies.map(cookie => `${cookie.name}=${cookie.value}`).join('; ');

            // Make a fetch request with the cookies included
            fetch('/some/path', {
                headers: {Cookie: cookieHeader}
            })

        } else {
            console.log('Error: ' + response.error)
        }
    })

service_worker.js

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {

// getCookies
if (message.action === 'getCookies') {
    // Get all cookies for this domain
    chrome.cookies.getAll({ domain: message.domain }, cookies => {
        if (chrome.runtime.lastError) {
            // Handle any errors
            sendResponse({ success: false, error: chrome.runtime.lastError });
        } else {
            // Return the cookies in the response message
            sendResponse({ success: true, cookies: cookies });
        }
    });

    // Return true to indicate that we will send a response asynchronously
    return true;
}

});

发布评论

评论列表(0)

  1. 暂无评论