Using Cookies with Firefox Extensions and JavaScript

Posted on 10 July 2007 by Johannes Fahrenkrug. Tags: JavaScript Programming Firefox Extensions
I'm working on a Firefox Extension at the moment and I had to read and write cookies with that extension. To make a long story short, this is how you do it (in the JavaScript code of your extension):
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;
    }
  }
}
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);

cookieSvc.setCookieString(cookieUri, null, 
  "key=value", null);
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:
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?
To remove all the cookies in the browser:
Components.classes["@mozilla.org/cookiemanager;1"]
  .getService(Components.interfaces.nsICookieManager)
  .removeAll();
For this, the nsICookieManager source was insightful. Well, so much for cookies and Firefox Extensions, I hope this was useful to someone.

Comments

Phil Crosby said...

Excellent, thank you Johannes!

February 09, 2008 01:01 AM

vartika said...

This is quite useful. Thanks for posting such useful document

January 30, 2008 12:49 PM

Comments

Please keep it clean, everybody. Comments with profanity will be deleted.

blog comments powered by Disqus