Firefox 插件:让内容脚本检索插件脚本存储的数据(如果可能,使用上下文菜单)

Firefox addon: Have content script retrieve data stored by addon script (using a context menu if possible)

我尝试构建一个可以做到这一点的基本插件:

所以我考虑使用上下文菜单并让

我遇到的问题是数据类型以及将存储的数据发送到内容脚本。

这是我目前的情况:

main.js

var cm = require("sdk/context-menu");
var ss = require("sdk/simple-storage");

// The following gave me a 'Message: SyntaxError: missing ; before statement'
// So I guess I cannot set the stored data like this to be reachable all over 
// the addon script...
//   var ss.storage.storedFormData = null;

var copyItem = cm.Item({
      label: "copy",
      data: null
});

// Then here I have 'data is not defined'
var pasteItem = cm.Item({
      label: "paste",
      data: ss.storage.storedFormData
});

var searchMenu = cm.Menu({
      label: "Choose what you want to do",
      contentScriptFile: [
            data.url('jquery-1.11.2.min.js'),
            data.url('content-script.js')
      ],
      onMessage: function (formData) {

          console.log('Storing formData');
          var ss.storage.storedFormData = JSON.stringify(formData);

      },
      items: [copyItem, pasteItem]
});

内容-script.js

self.on("click", function (node, data) {

    if (data === null) {
        // 'data' is null = get data from page
        var formData = new Object();

        // Get elements on page
        formData.element1 = $('input#elementId1').val();
        formData.element2 = $('input#elementId2').val();
        formData.element3 = $('input#elementId3').val();

        // Send data to addon script to be stored
        self.postMessage(formData);

    } else {
        // 'data' is not null, populate the page with data

        // Retrieve the data
        formData = JSON.parse(data);

        // Fill the fields with the data
        $('input#elementId1').val(formData.element1);
        $('input#elementId2').val(formData.element2);
        $('input#elementId3').val(formData.element3);
    }

});

好的,我运行插件,在进行评论中描述的修改后。它在整个会话中将第一个复制的 formData 粘贴到特定会话中,即使复制了后续值也是如此。问题是简单存储变量 ss 的值仅在启动时更新,而菜单项 pasteItemvalue 属性 在创建时被初始化,这也是在开始时间。解决方案是更换

var ss.storage.storedFormData = JSON.stringify(formData);

pasteItem.data = ss.storage.storedFormData = JSON.stringify(formData);