Work with the simple-prefs module and export the values to a script stored in the data folder

安稳与你 提交于 2019-12-11 03:25:45

问题


I'm currently trying to add some preferences to a Firefox add-on. To do so, I'm playing with the new "simple-prefs" module. (Simple-Prefs on the Mozilla Blog)

The documentation is not very detailed and I face some problems understanding how I can retrieve the value attached to an option and export it to a JS script present in my data folder.

Let's say that I have only one optional setting in my addon, a boolean one, then my packages.json will look like this:

{
  "name": "test",
  ...
  "preferences": [{
    "type": "bool",
    "name": "option1",
    "value": true,
    "title": "Desc Option 1" 
  }]
}

Here is my main.js file [UPDATED]:

var pageMod = require("page-mod");
const data = require("self").data;
const prefSet = require("simple-prefs");  //Simple-prefs module

var option1 = prefSet.prefs.option1;     //get the value for option1

function onPrefChange(prefName) {        //Listen for changes

   var prefName = prefSet.prefs[prefName];
                      }

prefSet.on("option1", onPrefChange);


exports.main = function() {
  pageMod.PageMod({ 
    include: ["https://mail.google.com/*","http://mail.google.com/*"],
    contentScriptWhen: 'ready',
    contentScriptFile: [data.url("jquery.js"),data.url("script.js")],
    onAttach: function(worker)
        {
      worker.postMessage( option1 );
        }
    });
}

How can I retrieve the value attached to "option1" and export it in order to call it in my "script.js" file?


回答1:


As usually, content scripts don't have access to the API - they can only receive messages from your extension's scripts. Here you would do:

pageMod.PageMod({ 
  include: ["https://mail.google.com/*","http://mail.google.com/*"],
  contentScriptWhen: 'ready',
  contentScriptFile: [data.url("jquery.js"),data.url("script.js")],
  onAttach: function(worker)
  {
    worker.postMessage(backtop);
  }
});

And in the content script you would have the following code:

self.on("message", function(data)
{
  alert("Received option value: " + data);
});

This message arrives asynchronously meaning that your content script won't know the option value initially - but that's how content scripts work.



来源:https://stackoverflow.com/questions/9425013/work-with-the-simple-prefs-module-and-export-the-values-to-a-script-stored-in-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!