[Project_owners] Re: protecting preferences

GuruJ GuruJ at mbox.com.au
Fri Nov 19 23:50:48 EST 2004


HJ wrote:

> Neil wrote:
<snip>
>> Why not copy the important ones to user.js?
> 
> 
> Thanks Neil, but I am aware of user.js. My main problem is that I have 
> to ask 'end-users' to copy the preferences from prefs.js to user.js just 
> to prevent them from losing prefs, and that sucks. Btw, all user set 
> preferences in prefs.js are imporant if you ask me.

Why not build an extension that does the job for you?  Use the 
"@mozilla.org/preferences-service;1" component to go through all 
preferences and copy the user-set ones to a backup file.  To restore the 
last backup, just reverse the process.

For example, this code should save user-set preferences (no guarantees, 
I'm copying and pasting without testing here):

// ====================================================================
// get list of preferences
var prefService = 
Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService);
var prefBranch = prefService.getBranch(null);
var prefArray = prefBranch.getChildList("" , prefCount);

i = 0;
while(i < prefCount.value) {

   // if preference has a user value set
   if(prefBranch.prefHasUserValue(prefArray[i])) {

     const nsIPrefBranch = Components.interfaces.nsIPrefBranch;

     try {
         switch (prefBranch.getPrefType(prefArray[i])) {
             case nsIPrefBranch.PREF_INT:
                 // convert to string literal and save
                 savePref( "int", 
prefBranch.getIntPref(prefArray[i]).toString() );
                     break;
             case nsIPrefBranch.PREF_BOOL:
                 // convert to string literal and save
                 savePref( "bool", 
prefBranch.getBoolPref(prefArray[i]).toString() );
                     break;
             case nsIPrefBranch.PREF_STRING:
                 // convert to string literal and save
                 savePref( "string", 
prefBranch.getComplexValue(prefArray[i], nsIPrefLocalizedString).data );
                     break;
             default:
                 alert(gBundle.getString(msgErrorElement) + prefArray[i]);
         }
     }
     catch (e) {
         // catch errors where pref exists but has no valuee
     }

   }
}

function savePref( type, value ) {
   // serialise to file or RDF here...
}
// ====================================================================

-- GuruJ.


More information about the Project_owners mailing list