yegor256
yegor256

Reputation: 105043

How to read profile preferences from Firefox add-on?

I'm doing this (Firefox 66.0.5, MacOS):

var prefs = Components.classes['@mozilla.org/preferences-service;1']
  .getService(Components.interfaces.nsIPrefBranch);
var x = pref.getCharPref('extensions.foo.x');

I'm getting this:

JavaScript error: moz-extension://9390a488-d749-d140-91b6-fb1b2a86053f/foo.js,
line 1: TypeError: Components.classes is undefined

What is the right way to read the preferences of the profile?

I tried this:

var prefs = Components.classesByID['@mozilla.org/preferences-service;1']
  .getService(Components.interfaces.nsIPrefBranch);

And got this:

JavaScript error: moz-extension://ebac8f96-717d-0c4b-b2d3-a7d6f3515843/auth.js,
line 1: TypeError: Components.classesByID is undefined

Upvotes: 2

Views: 844

Answers (1)

Makyen
Makyen

Reputation: 33296

WebExtensions are very limited in their ability to make changes to user preferences. There are a few, currently 14, that you can affect through the browserSettings API. There are others which are effectively changed through other WebExtension APIs (e.g. proxy), but nothing directly. Unfortunately, there's no direct way to read or set user preferences from a WebExtension. The capability to adjust user preferences directly was only available to the older styles of add-ons (all removed as of Firefox 57).

As to your use of Components and the specific errors which you are getting, please see my answer to Unable to use Components in WebExtensions: get “ReferenceError: Cu is not defined” for more detail. The use of Components is just not possible in a WebExtension.

The only way that I can think of that it might be possible to adjust preferences in a release version of Firefox is to use Native messaging to communicate to a native application which you also install. After Firefox exits/stops/is shutdown, the native application could read and change the configuration files in the profile directory for the Firefox profile being run. It could then restart Firefox.

In the Nightly and Developer Edition versions of Firefox, it should still be possible to use a WebExtensions Experiment, which would permit you to make the preference changes you desire using the Components interface. However, that's not a viable solution if this is an extension you want to distribute publicly.

Upvotes: 2

Related Questions