5

I am developing a Firefox extension and need to access a specific cookie from a specific domain. I have this code which fetches all cookies for all domains, how do I request only the cookie that I am looking for.

var {Cc, Ci} = require("chrome");

var cookieManager = Cc["@mozilla.org/cookiemanager;1"].getService(Ci.nsICookieManager);

var count = cookieManager.enumerator;

while (count.hasMoreElements()){
    var cookie = count.getNext();
    if (cookie instanceof Ci.nsICookie){
        console.log(cookie.host);
        console.log(cookie.name);
        console.log(cookie.value);
    }
}

To sum up, I am able to find the cookie that I am looking for with the code above but I don't want to have to iterate through all of the cookies from all domains.

Manatok
  • 5,506
  • 3
  • 23
  • 32

1 Answers1

6

You can use nsICookieManager2 interface (the original nsICookieManager interface was frozen and couldn't be changed which is why this extended version was created):

var cookieManager = Cc["@mozilla.org/cookiemanager;1"]
                      .getService(Ci.nsICookieManager2);
var count = cookieManager.getCookiesFromHost("example.com");

Note: the concept of frozen interfaces was dropped in Gecko 2.0 (Firefox 4). Since then some interfaces similar to nsICookieManager/nsICookieManager2 have been unified - so in a future Firefox version nsICookieManager2 might go away as well, all the functionality will be exposed on nsICookieManager then.

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
  • Could you please provide an example of how to fetch the cookies from iterator that `getCookiesFromHost` returns? – MeLight Aug 12 '13 at 08:25
  • 1
    A complete example can be found here: https://developer.mozilla.org/en-US/docs/Code_snippets/Cookies – MeLight Aug 12 '13 at 08:41
  • @Wladimir Palant Is there a way to remove all the cookies from firefox extension? – Muthu Mar 14 '16 at 12:25
  • @muthu: How about using [nsICookieManager.removeAll()](https://developer.mozilla.org/en-US/docs/Mozilla/Tech/XPCOM/Reference/Interface/nsICookieManager#removeAll%28%29)? – Wladimir Palant Mar 14 '16 at 12:35
  • Is there a way to obtain all the cookies of firefox browser instead of getting cookies based oh hostName – Muthu Mar 14 '16 at 13:11
  • @muthu: Well, if you don't want to read the documentation - how about reading the text of this question? – Wladimir Palant Mar 14 '16 at 13:50