Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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']
}
like image 570
Bob van Ham Avatar asked Aug 01 '14 11:08

Bob van Ham


1 Answers

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);
  }
});
like image 124
kapex Avatar answered Sep 18 '22 19:09

kapex