This MDN page helped a lot: Code Snippets: Cookies. So what about writing cookies? Easy:var ios = Components .classes["@mozilla.org/network/io-service;1"] .getService(Components.interfaces.nsIIOService); var cookieUri = ios .newURI("http://www.uri_of_the_cookies.com/", null, null); var cookieSvc = Components .classes["@mozilla.org/cookieService;1"] .getService(Components.interfaces.nsICookieService); var cookie = cookieSvc.getCookieString(cookieUri, null); if (cookie == null || cookie.length < 1) { //no cookie set for this uri } else { var cookieArray = cookie.split("; "); //loop through the different cookies //(key/value pairs) for this URI for (var i = 0; i < cookieArray.length; i++) { var kvPair = cookieArray[i].split("="); if (kvPair.length > 1 && kvPair[0] == "NameOfTheCookieImLookingFor" && kvPair[1].length > 0) { //the value is in kvPair[1] break; } } }
For this I got a very helpful hint from the Mozilla Sessionmanager source code (just search for setCookieString). There's lot of other interesting stuff in there, I'm sure. And last but not least: What about removing cookies? Quite easy as well:var ios = Components .classes["@mozilla.org/network/io-service;1"] .getService(Components.interfaces.nsIIOService); var cookieUri = ios .newURI("http://www.uri_of_the_cookies.com/", null, null); var cookieSvc = Components .classes["@mozilla.org/cookieService;1"] .getService(Components.interfaces.nsICookieService); cookieSvc.setCookieString(cookieUri, null, "key=value", null);
To remove all the cookies in the browser:Components.classes["@mozilla.org/cookiemanager;1"] .getService(Components.interfaces.nsICookieManager) .remove(".mydomain.com", //the domain "nameOfCookie", //the name of the cookie "/path", //the path of the cookie, ie "/" false); //should cookies from this host //be blocked permanently?
For this, the nsICookieManager source was insightful. Well, so much for cookies and Firefox Extensions, I hope this was useful to someone.Components.classes["@mozilla.org/cookiemanager;1"] .getService(Components.interfaces.nsICookieManager) .removeAll();
Comments
vartika said...
This is quite useful. Thanks for posting such useful document
January 30, 2008 12:49 PM
Phil Crosby said...
Excellent, thank you Johannes!
February 09, 2008 01:01 AM