I am building and extension with Firefox's Addon SDK (v1.9).
My application is supposed to remove cookies as they are added (or changed) based on a database of matching URIs.
I accomplish this task by adding an observer to 'cookie-changed' and implementing nsICookie to identify matching cookies and nsICookieManager to remove the cookie if a match is found.
Problem
I need know what website (URL) each cookie was added / changed from.
Unfortunately, by the time the cookie manager sends the cookie-changed
notification that information is already lost - the cookie manager only knows which host the cookie is added for (and it might not be the host of the page setting the cookie if domain
parameter was used). It might even be that there was no URL in the first place, e.g. if the cookie is set by an extension.
What you could do is register an observer for the http-on-examine-response
notification. You can look at the Set-Cookie
header of the channel as well as the channel URL so when cookie-changed
notification is sent later you will know which website is responsible. Something like this:
var observer = require("observer-service");
observer.add("http-on-examine-response", function(subject, data)
{
subject.QueryInterface(Ci.nsIHttpChannel);
var cookieNames = [];
// There can be more than one Set-Cookie header, cannot use getResponseHeader
subject.visitResponseHeaders(function(header, value)
{
if (header.toLowerCase() == "set-cookie")
{
var match = /^([^\s=]+)=/.exec(value);
if (match)
cookieNames.push(match[1]);
}
});
if (cookieNames.length)
{
var url = channel.URI.spec;
// Remember that this url set the cookies or just clear the header
if (!isAllowedToSetCookies(url, cookieNames))
channel.setResponseHeader("Set-Cookie", "", false);
}
});
Note: This code hasn't been tested.
Documentation: observer notifications, nsIHttpChannel