Observing Cookie changes in Firefox Extensions

Preferences MDC has an example for setting a “nsPref:changed” observer but I needed to watch some cookies as well for FireVortex. I was unable to find a clear cut example so a slight modification and it seems to work:


function CookieListener(func) {
var cl = Components.classes['@mozilla.org/observer-service;1']
.getService(Components.interfaces.nsIObserverService);

this.register = function() {
cl.addObserver(this, "cookie-changed", false);
};

this.unregister = function unregister() {
if (cl) cl.removeObserver(this,'cookie-changed');
};

this.observe = function(subject, topic, data) {
if (topic == "cookie-changed")
func(subject);
};
}

var myListenerCookie = new CookieListener(
function(subject) {
let cookie = subject.QueryInterface(Components.interfaces.nsICookie);
if (cookie.name == "mycookiename"
|| cookie.host == "mycookiehost.com") {
//update whatever
}
});

myListenerCookie.register();

*EDIT…

found this throws a random Error: Components is not defined
added
if (typeof Components == 'undefined') return;

as a fail-safe… not sure why this is happening…

*DOUBLE EDIT…

my bad… don’t keep the profile/extensions folder under application data open during an update ;)

This entry was posted in FireVortex and tagged , . Bookmark the permalink.

Leave a Reply