I am attempting to use preferences in a Firefox extension. I am able to create and read these, but when I attempt to run a function when they are changed I encounter a problem. I am using the suggested framework from MDN (with modifications so it does what I want).
This is the exact code here:
observe: function(aSubject, aTopic, aData) {
if (aTopic != "nsPref:changed")
{
return;
}
switch (aData) {
case "username":
var prefManager = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
var username = prefManager.getCharPref("extensions.alexandriauplink.username");
// extensions.myextension.pref1 was changed
break;
case "password":
var prefManager = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
var password = prefManager.getCharPref("extensions.alexandriauplink.password");
alert(password);
break;
}
var password = prefManager.getCharPref("extensions.alexandriauplink.password");
var username = prefManager.getCharPref("extensions.alexandriauplink.username");
alert( "username:" + username +"|" + "password:" + password);
}
The problem is that when I change the preferences in the option dialogue, this function is triggered 3 times for each preference which is changed.
Thank you in advance if you are able to be of assistance.
As a commenter pointed out, this was caused by multiple windows of firefox being open – each one was firing the event.