Visit Mozilla.org

Code snippets:Cookies

From MDC


Contents

[edit] Reading existing cookies

var ios = Components.classes["@mozilla.org/network/io-service;1"]
            .getService(Components.interfaces.nsIIOService);
var uri = ios.newURI("http://www.google.com/", null, null);
var cookieSvc =
   Components.classes["@mozilla.org/cookieService;1"]
             .getService(Components.interfaces.nsICookieService);
var cookie = cookieSvc.getCookieString(uri, null);

Note: Cookies, with their names and values, can also be iterated via XPCOM.

[edit] Removing all cookies

The following code demonstrates how to remove all cookies from Firefox/Seamonkey.

Components.classes["@mozilla.org/cookiemanager;1"]
          .getService(Components.interfaces.nsICookieManager).removeAll();

[edit] Setting a cookie

The following code demonstrates how to set a cookie in Firefox.

    var ios = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
    var cookieUri = ios.newURI("http://www.yourplacewhereyouwanttosetthecookie.com/", null, null);
    var cookieSvc = Components.classes["@mozilla.org/cookieService;1"].getService(Components.interfaces.nsICookieService);

    cookieSvc.setCookieString(cookieUri, null, "your_key=your_value; your_next_key=you_next_value", null);

Note: If you want to set a persistent cookie, you will have to add an expiration date to the string in setCookieString yourself.

[edit] See also