Firefox SDK access preferences from content script

About

I'm working on a Firefox Add-on using the Firefox Add-on SDK. The add-on will be site specific and it will hide certain elements based on user preferences.

I already made this add-on a few years back, but with the new SDK things work a bit different.


Code

Because the add-on is site specific and I need to modify the content of the site I use the 'PageMod' module

[main.js]

pageMod.PageMod({
  include: "*.ipvisie.com",
  contentScriptFile: [
    data.url('jquery-1.11.1.min.js'),
    data.url('script.js')
  ]
});

This works great, jQuery is implemented and I can add and run javascript from script.js

I have declared the preferences in 'package.json' and this works great. I can access this from 'main.js'


Problem

My problem is that the ContentScript doesn't have access to the user preferences.

How can I gain access to the current preferences in my ContentScript 'script.js'?


Tried attempts

Attempt 1
First thing I tried was just to request the preference from the ContentScript

if (require('sdk/simple-prefs').prefs['somePreference'] == true) {
    alert('Pref checked');
}



Attempt 2
I read in the documentation that some read only parameters can be send with the ContentScript. This seemed to work, but when I changed my preferences the values were already set. Only if I would restart the browser the correct setting would be passed.

contentScriptOptions: {
    advertLink: require('sdk/simple-prefs').prefs['advertTop'],
    advertDay: require('sdk/simple-prefs').prefs['advertDay'],
    advertAdmart: require('sdk/simple-prefs').prefs['advertAdmart'],
    advertLink: require('sdk/simple-prefs').prefs['advertLink']
}

You should send the new preferences to the content script every time preferences got changed and not only at the scripts initialisation.

You can communicate with the content script via messages: Communicating With Content Scripts
Create a function that receives changed preference names and values and a preference change listener to send the changes to the script:

pageMod.PageMod({
  // ...
  onAttach: function(worker) {
    worker.port.on("prefChange", function(prefName, prefValue) {
      // update page ...
    });

    function onPrefChange(prefName) {
      self.port.emit("prefChange", prefName, require("sdk/simple-prefs").prefs[prefName]);
    }
    require("sdk/simple-prefs").on("", onPrefChange);
  }
});
链接地址: http://www.djcxy.com/p/80638.html

上一篇: 第一天!=“本月的第一天”

下一篇: 内容脚本中的Firefox SDK访问首选项