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.
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'
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'?
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);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With