Customizing Firefox – Advanced Autoconfig Files

We’re almost done with autoconfig files. My previous posts covered what an autoconfig file is and how to create one. Now we’re going to discover how truly powerful the autoconfig feature is.

I’ve been saying this over and over, but it’s worth repeating:

Autoconfig files are Javascript files that have full access to all components of Firefox.

This means we can use autoconfig files to change just about anything the browser that doesn’t involve the user interface (and there are even ways to change that).

So how do we access the various components? The best way to use those components is via a helper Javascript module called Services.jsm. Services.jsm provides shortcuts to access frequently used components within Firefox. So for instance, if you wanted to display an alert to a user from inside your autoconfig file, you could use:
[code type=”javascript”]
Components.utils.import("resource://gre/modules/Services.jsm");
Services.prompt.alert(null, "Title", "Message");
[/code]
nsIPromptService shows all the functions you can use to prompt a user, including confirmations as well as data input

Or what if you wanted to add a bookmark? Unfortunately, the bookmarks services isn’t in Services.jsm, but it’s easy to get:
[code type=”javascript”]
//
Components.utils.import("resource://gre/modules/Services.jsm");
var uri = Services.io.newURI("http://mike.kaply.com", null, null);
var navBookmarksService = Components.classes["@mozilla.org/browser/nav-bookmarks-service;1"]
.getService(Components.interfaces.nsINavBookmarksService);
navBookmarksService.insertBookmark(navBookmarksService.toolbarFolder, uri, -1, "Mike’s Blog");
[/code]
As you can see, you can pretty much do anything from an autoconfig file. I couldn’t even begin to scratch the surface. The best place to start looking is MDN (or just ask in the comments).

Before we finish up, I want to give one other code snippet that might be useful for folks. In a couple posts, we’ll be covering userChrome.css and userContent.css Putting these files in a user’s profile directory is a common way to do simple customization of the browser. Unfortunately that usually requires setting up a default profile (which is another thing we’ll be talking about in a few posts). By using an autoconfig file to write out these files, we avoid having to manually place them in each user’s profile:
[code type=”javascript”]
//
const Cc = Components.classes;
const Ci = Components.interfaces;
Components.utils.import("resource://gre/modules/Services.jsm");
var profileDir = Services.dirsvc.get("ProfD", Ci.nsILocalFile);
profileDir.append("chrome");
if( !profileDir.exists() || !profileDir.isDirectory() ) {
profileDir.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);
}
profileDir.append("userChrome.css");
var fos =
Cc["@mozilla.org/network/file-output-stream;1"].createInstance(Ci.nsIFileOutputStream);
fos.init(profileDir, -1, -1, false);
var css = "#context-setDesktopBackground { display: none;}";
fos.write(css, css.length);
fos.close();
[/code]
This example removes the menuitem that changes the desktop background.

Autoconfig files are VERY powerful, even more powerful then even I realized. In combination with userContent.css and userChrome.css, you can do a lot.

So when do you choose to use autoconfig files? The best thing about autoconfig files is how easy they are to get into Firefox. No need for an add-on or anything like that. You just drop in two files and you’re done. You can also put the configuration file on a server which makes things even easier. So you should choose autoconfig files when the changes you are making to Firefox don’t involve major changes to the user interface. You should also choose autoconfig files if you need to lock preferences (although you can lock preferences with the CCK – we’ll talk about that later).


Comments

56 responses to “Customizing Firefox – Advanced Autoconfig Files”

  1. Tyler Riti Avatar
    Tyler Riti

    I’m trying to add popup and cookie exceptions to my autoconfig file but I can’t get it to work. Here’s what I’ve tried:

    Components.utils.import(“resource://gre/modules/Services.jsm”);
    var uri = Services.io.newURI(“http://utexas.edu”, null, null);
    Services.perms.add(uri, “popup”, 1);
    Services.perms.add(uri, “cookie”, 1);

    It generates no errors (that I’m aware of) but neither does it add the exceptions. Everything else in the autoconfig file is getting applied (numerous lockPref() and pref() calls earlier in the file) and I can even get an alert to appear after importing the Services module so I guess that I’m either building the URI or adding the exception incorrectly (or both).

    1. Mike Kaply Avatar
      Mike Kaply

      I just cut and pasted your exact code and put it into an autoconfig file and it worked for me. Did you try it by itself in an autoconfig file? (If you do decide to cut and paste to retest, don’t forget to fix the double quotes that wordpress messes with)

      1. Tyler Riti Avatar
        Tyler Riti

        Indeed it does… I tracked it down to one pref in the autoconfig file:
        pref(“privacy.clearOnShutdown.siteSettings”, true);

        “Why yes, of course!” Firefox is launched (for the first time), the autoconfig settings get applied, Firefox relaunches itself and deletes the popup and cookie exceptions as instructed.

        I guess that’s what I get for being overly paranoid about browsing privacy. 🙂

        Thanks for the response.

      2. Hi Mike, This is exactly what I’m looking to implement, but as the first post said it didn’t work – no errors but Firefox just wouldn’t load. I tried putting it in it’s own autoconfig file and still didn’t work. I’m running Firefox 36 on windows xp SP3. Any ideas? I’m just trying to add a single popup exception and deploy to multiple users. I’d just send the new config file to replace the old one.

        1. Mike Kaply Avatar
          Mike Kaply

          can you put a

          try {
          // CODE TO SET PERMISSIONS
          } catch (e) {
          Components.utils.reportError(e);
          }

          Then firefox will start and you can look at the console with Ctrl+Shift+J.

          Let me know what the error is.

          1. Here is the error I recieve:
            Could not read chrome manifest ‘file:///C:/Program%20Files/Mozilla%20Firefox/chrome.manifest’.
            Could not read chrome manifest ‘file:///C:/Program%20Files/Mozilla%20Firefox/browser/extensions/%7B972ce4c6-7e08-4474-a285-3208198ce6fd%7D/chrome.manifest’.
            1465009480559 Services.HealthReport.HealthReporter WARN Saved state file does not exist.
            1465009480559 Services.HealthReport.HealthReporter WARN No prefs data found.
            Key event not available on some keyboard layouts: key=”c” modifiers=”accel,alt” browser.xul

          2. Mike Kaply Avatar
            Mike Kaply

            Those are the normal Firefox errors, nothing unique.

            Can you open a bug at cck2.freshdesk.com with the exact code from your AutoConfig?

  2. […] do choose to use userContent.css or userChrome.css, I would suggest the methods I talked about in my earlier post on autoconfig. Then you don’t have to mess with the default […]

  3. Anthony Lanni Avatar
    Anthony Lanni

    OK, I’ve got a question for you. I’m trying to set the cache directory to point to a location outside the user home directory. Using the autoconfig file, I set browser.cache.disk.parent_directory to the directory I want: inside Firefox’s about:config page I can see that setting, italicized. However, the cache stays right where it is.

    If I set it manually in the prefs.js file, the next time Firefox starts the cache goes to the preferred location. However, upon quitting Firefox writes out the preferences and removes that pref.

    Any ideas?

    1. Mike Kaply Avatar
      Mike Kaply

      What platform are you on? If you are on Windows, did you set the preference with double slashes?

      See:

      http://kb.mozillazine.org/Browser.cache.disk.parent_directory

      1. Anthony Lanni Avatar
        Anthony Lanni

        I’m on Red Hat Enterprise Linux, running Firefox 10.0.3. I have Windows machines in the company, but I have not tested to see if the cache redirection works on them.

        thx
        anthony

        1. Mike Kaply Avatar
          Mike Kaply

          Sorry for the delay. I’ve tested this on Windows and it’s working for me.

          Are you setting the cache in the config file or via a remote config file?

          Can you post the exact line you are using to set/lock the prefs?

  4. Cedric Hauwel Avatar
    Cedric Hauwel

    Hi,

    First, many thanks for your “musings” that have been highly time-saving for me.

    Is there a way to get a reference to the browser object from the autoconfig file in order to add tab-related event handlers ?

    Regards.

    1. Mike Kaply Avatar
      Mike Kaply

      The autoconfig is processed very early, so anything browser related wouldn’t be setup yet.

      Something like that would be best handled via an add-on.

  5. Venkata Avatar
    Venkata

    Referring to your post: “This means we can use autoconfig files to change just about anything the browser that doesn’t involve the user interface (and
    there are even ways to change that). ”
    Since long, I have been trying to disable buttons in Tools -> Options and also disable the whole tab like “Advanced” tab. Can I achieve this using auto config files.
    Your suggestions in this regards will be really helpful.

    1. Mike Kaply Avatar
      Mike Kaply

      When it comes to user interface, most of the time it’s easier to just write an extension to do it.

      Some preference options can be disabled via preferences (if you lock the preferences, it disables the item).

      Another option is to write out the file userChrome.css to disable things. That can be done via autoconfig.

  6. any chance you have something to change to a new profile?
    for example I want to run firefox esr and firefox nightly with two different profiles. and it would be great if one could automate this.

    1. Mike Kaply Avatar
      Mike Kaply

      You can bring up the profile manager by typing:

      firefox -profile-manager

      Uncheck the box that says “Don’t ask at startup”.

      Then create a new profile for your Nightly.

      When you start Firefox, you can start it with “firefox -p “Profile name” -no-remote and then you can start the second Firefox the same way.

      1. I was thinking of distributin the two firefox versions to other users than me. so idealy the profile would just be default in firefox esr and in nightly a new profile created and used automaticly. so without the user doing anything 😉

        1. Mike Kaply Avatar
          Mike Kaply

          Ah.

          The only way I know to do that would be to have the shortcuts for the two Firefox versions point to different directories for their profiles.

          If you start Firefox with -profile “PATH” you can specify where the profile is initially created.

          So you could have icons for the different firefoxes like:

          firefox -profile “C:\Users\foo\ESR”

          and

          firefox -profile “C:\Users\foo\Nightly”

          That’s the only thing that I can think of…

          1. not a bad idea. I will test that out.
            I also posted an argument change in mozilla suggestion box about a autocreat profile.

            many thanks 😉

          2. works great!
            C:\Programfiler\Nightly\firefox.exe -profile “%appdata%\Mozilla\Firefox\Profiles\thor” -no-remote

            not sure if -no-remote is necessary

            many thanks 😉

  7. Piyush Rai Avatar
    Piyush Rai

    I am trying to hide Sync,Security,Privacy and advanced tab.
    Firefox version is 19.0
    I think this can be achieved via creating userchrome.css file and saving it under chrome folder. However, i am not sure how to write codes in this file. Also, there is no chrome folder in the location where the executable of firefox exists.
    Please help me.

    1. Mike Kaply Avatar
      Mike Kaply

      userChrome.css goes into the profile directory, not the Firefox directory.

      See:

      http://kb.mozillazine.org/index.php?title=UserChrome.css&printable=yes

      1. Piyush Rai Avatar
        Piyush Rai

        Thanks for the response. I checked the link but there is no mention that i can hide the Security or Privacy tab under Firefox options. Please advise if this is possible using .css file. If yes, please help me with an example code which can hide any of these option so that i can use it to hide other options as per the requirement.
        Thanks in advance 🙂

        1. Mike Kaply Avatar
          Mike Kaply

          You’ll need to do some research to find the answers you’re looking for. You’ll need to find the IDs of the elements you want to hide. From http://mike.kaply.com/2012/03/30/customizing-firefox-default-profiles/

          There are so many things you can do with this file, I couldn’t even begin to describe them here. You can hide menuitems, change parts of the UI, etc. If you choose to hide something, it’s better to use visibility: collapse than display: none. Messing with display can cause very strange results in Firefox. If you’re interested in figuring out the IDs of the various elements of the UI, check out the DOM Inspector. You can also just browser through the source code. browser-menubar.inc and browser-context.inc are particularly useful.

  8. […] You can add this code to your autoconfig file. […]

  9. What I want is the ability to set three pages to open each in a separate tab and set the focus to a particular tab.

    I just made the following up (stuff in caps) for lack of any examples

    user_pref(browser.startup.tab.TABNAME.TAB1.link”, “www.microsoft.com”);
    user_pref(browser.startup.tab.TABNAME.TAB2.link”, “www.google.ca”);
    user_pref(browser.startup.tab.TABNAME.TAB3.link”, “www.outlook.com”);
    user_pref(browser.startup.tab.SETFOCUS.TAB2

    obviously the tab gets it’s name from the url so you wouldn’t use that but is there a way that you can think of to get the desired effect

    Logically speaking… Create an index of three and set focus to the desired tab index.

    1. Mike Kaply Avatar
      Mike Kaply

      There’s no way to set the default tab (I believe it is always the last one), but you can set multiple homepages like this:

      pref(“browser.startup.homepage”, “http://www.yahoo.com|http://www.google.com|http://www.digg.com”);

  10. dennyhalim.com Avatar
    dennyhalim.com

    profileDir.append did not do exactly what it said.
    it does not append. it overwrite the file.

    how can i append only few lines into the file?

    tnx.
    dny

    1. Mike Kaply Avatar
      Mike Kaply

      profileDir.append appends a file name to a profileDir.

      What exactly are you trying to do? What file are you trying to append to?

  11. I am not a coder. I have a question about the alert sound in firefox.

    I am a lead of a helpdesk team. We provide chat support using a web ticketing tool which has limitations.

    Our team members hear a very faint “pop” sound when there is a chat window from a user. But this is too faint.
    I would want to know the source file of sound in Firefox. So that I could change the sound’s source file to a louder alert sound.

    Any ideas?

    1. Mike Kaply Avatar
      Mike Kaply

      I don’t think that sound is coming from Firefox. You would need to check with the vendor.

    2. Why not just raise the volume on the computer ?
      Unless you want a different sound.
      Also, if you are using Microsoft windows, you can set different sounds for different events, with provided or custom files.
      If you use chatzilla (with seamonkey or separately), you can configure it to beep or play whatever sound file you like, for various events.

  12. Mike,

    In my case the user’s profile has already been created so leveraging the autoconfig to set the userChrome.css is perfect! Your example worked flawlessly in my environment, however I need to write 4 different settings to the userChrome.css. I need a little assistance figuring this out as I kept getting all 4 lines on just a single line in the userChrome.css file.

    Thanks!

    -Steve

    1. Okay I figured it out. I had to place the Unicode escape character between the entries.

      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Unicode_escape_sequences

      For instance line 14 now hides the Show Password button, removes the update button from the about screen, and shows the menu bar (file, edit, etc).

      var css = “#togglePasswords {visibility: hidden;}\u000D#aboutDialog #updateBox {display:none!important;}\u000D#mail-toolbar-menubar2[autohide=”+”\”true\”] { overflow-x: visible !important; }\u000D#mail-toolbar-menubar2[autohide=”+”\”true\”] { overflow-y: visible !important; }”;

      1. Mike Kaply Avatar
        Mike Kaply

        Glad it’s working for you. I was going to suggest using “\n”

  13. Sebastian Avatar
    Sebastian

    Hi Mike,
    first i’d like to thank you for all the great informations about configuring Firefox. I used it a lot to get our Firefox deployments running with the settings we need.

    Now I would like to know if it is possible to load a “Security Device” via autoconfig file.

    Using the GUI you will get there by: Tools –> Options –> Advanced –> Security Devices –> Load

    Because I need to install a PKCS11 Module I found this: https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/PKCS11/Module_Installation#Installing_PKCS11_Modules_Using_nsIPKCS11_

    But is is for use within an Extension I think. Unfortunately I have far to little understanding of that, so I would appreciate your help.

    Thnaks in advance

    1. Mike Kaply Avatar
      Mike Kaply

      Yes.


      try {
      var pkcs11 = Components.classes["@mozilla.org/security/pkcs11;1"].getService(Components.interfaces.nsIPKCS11);
      pkcs11.addModule("The name you want to use", "NATIVE PATH", 0, 0);
      } catch (e) {
      // Ignore errors
      }

      1. Hi,

        I was customizing Firefox 38.2.1 for windows 7 in order to deploy it for my company. Also, i am looking for display automatically the menu bar when user will launch Firefox. I search in about:config in order to include the parameter in mozilla.cfg but i don’t find the right one. May you help me, giving me the preference in about config or by an other way?

        Thank you

        David

        1. Mike Kaply Avatar
          Mike Kaply

          Unfortunately this is not something that can be done via about:config. The CCK2 supports it. Or if you are using AutoConfig, I could give you some code to do it.

      2. John C Vander Voort Avatar
        John C Vander Voort

        I have added these lines to my CFG file and it is not adding anything to the security devices. Does this still work in the current versions? Is there anyway to add the catch error and where would I go to find it.

        1. Mike Kaply Avatar
          Mike Kaply

          The code I gave you does catch the error.

          Instead of //ignore errors, change it to

          Components.utils.reportError(e) and it should show the error on the console.

          1. Hi Mike,

            I’m hoping maybe you can help me with this one. I’m trying to add your code above to my Mozilla.cfg file to automatically add PKCS for ActivClient, but it’s giving me an error as shown below:

            Code in Mozilla.cfg:
            try {
            var pkcs11 =
            Components.classes[“@mozilla.org/security/pkcs11;1”].getService(Components.interfaces.nsIPKCS11);
            pkcs11.addModule(“ActivClient”, “C:\Program Files\HID Global\ActivClient\acpkcs211.dll”, 0, 0);
            } catch (e) {
            Components.utils.reportError(e)
            }

            Error I receive in the browser console:
            Components.classes[‘@mozilla.org/security/pkcs11;1’] is undefined Mozilla.cfg:28
            Mozilla.cfg:28:1

            Any help is greatly appreciated!

            – Mike

          2. Mike Kaply Avatar
            Mike Kaply

            What version of Firefox are you using?

  14. Mathieu Aït Azzouzene Avatar
    Mathieu Aït Azzouzene

    Hello Mike,

    Your code to add bookmarks works fine!…Except it adds the bookmarks everytime we launch Firefox without checking if it already exists.

    Is there a way to get rid of this issue?

    1. Mike Kaply Avatar
      Mike Kaply

      You would have to set some sort of preference to keep track of the fact that the bookmarks were added.

      I would recommend using the CCK2 and it will take care of this for you.

  15. Some Guy Avatar
    Some Guy

    >> Autoconfig files are Javascript files that have full access to all components of Firefox.

    Yes. However as of version 62.0.2, the autoconfig is Sandboxed which somethings are no longer accessible from the autoconfig file.

    You can get around this by adding:
    pref(“general.config.sandbox_enabled”, false);
    to the .js file in default/pref.

  16. Rishabh Aggarwal Avatar
    Rishabh Aggarwal

    Is it possible to auto install an add-on using this auto config?

  17. Mark T. Avatar
    Mark T.

    Thank you, Mike, for providing this valuable information to the community. I imagine it’s been a benefit to many over the past several years…
    You mentioned,
    “Autoconfig files are Javascript files that have full access to all components of Firefox.”
    On that note, I’ve been having significant trouble getting setInterval() to work in this scripting context on FF ESR 68.10.0; with “ReferenceError: setInterval is not defined” coming back to the console at every turn.
    Is there some way of addressing the need for a timer of this type in these scripts, or is there nothing more available for use beyond the greatly-delimited set of functions listed here:
    https://support.mozilla.org/en-US/kb/customizing-firefox-using-autoconfig#w_functions-of-autoconfig
    Thanks again.

    1. Mike Kaply Avatar
      Mike Kaply

      Try adding this line:

      Components.utils.import(“resource://gre/modules/Timer.jsm”);

      setInterval is only available in a window context so you need to import it.

      1. Mark T. Avatar
        Mark T.

        Good call, Mike: It worked 🙂

        One more question, if I might…

        Any idea as to why importing the AddonManager in like manner:

        Components.utils.import(“resource://gre/modules/AddonManager.jsm”);

        always returns:

        “NS_ERROR_NOT_INITIALIZED: AddonManager is not initialized AddonManager.jsm”

        ???

        Thanks again —

        1. Mike Kaply Avatar
          Mike Kaply

          Autoconfig runs way to early to use the AddonManager.

          You can take a look at the CCK2 source code to see how to do this. You have to use an observer to wait for later in startup

          https://github.com/mkaply/cck2wizard/blob/master/cck2/modules/CCK2.jsm#L746

  18. […] found this code on Michael Kaply’s Homepage and slightly modified it in the third line from below to suit your […]

  19. Mike, thank you for your articles about AutoConfig. Your comment here about Components.utils.import(“resource://gre/modules/AddonManager.jsm”) provided exactly the information I needed to have a way to automatically load addons from a local directory.

    For those interested in developing addons without having to load them manually every time please go to: https://github.com/tsaost/autoload-temporary-addon

Leave a Reply

Your email address will not be published. Required fields are marked *