【问题标题】:Firefox Addon SDK - pageMod update contentScriptOptions?Firefox 插件 SDK - pageMod 更新 contentScriptOptions?
【发布时间】:2015-03-27 07:40:10
【问题描述】:

我正在使用main.js 中的以下代码向example.com 上的页面添加内容脚本:

var self = require("sdk/self");
var pageMod = require("sdk/page-mod");

pageMod.PageMod({
        include: "https://example.com/*",
        contentScriptWhen: "ready",
        contentScriptFile: [
            self.data.url("example.js"),
        ],
        contentScriptOptions: {
            myString: 'helloWorld'
        }
    });

如果我设置了一个工作程序或事件侦听器,告诉main.js 更新myString 的值(可从使用self.options.myString 的内容脚本访问),我如何在example.js 内容脚本中反映该更改为下一个example.com 页面加载?

我尝试使用新的myString 值再次调用pageMod.PageMod 函数,但这会导致example.js 在页面上运行两次。

编辑:

我已经实现了Port API,但现在我被困在如何更新contentScriptOptions 传递给内容脚本的对象上。

/* main.js */
var self = require("sdk/self");
var pageMod = require("sdk/page-mod");

pageMod.PageMod({
    include: "https://example.com/*",
    contentScriptWhen: "ready",
    contentScriptFile: [
        self.data.url("example.js"),
    ],
    contentScriptOptions: {
        myString: 'foo'
    },
    onAttach: function(worker) {
        worker.port.on("updateOptions", function(data) {

            // how to replace myString with value from data.myString?

        });
    }
});

/* example.js */
self.port.emit('updateOptions', { myString: 'bar' });

【问题讨论】:

  • 请注意,您作为contentScriptOptions 传递的对象不能包含任何函数。

标签: javascript firefox firefox-addon-sdk


【解决方案1】:

您需要端口 API。

在您的内容脚本中,emit 监听 PageMod 将收到的消息。

/* example.js */  
self.port.emit("nameForTheMessage", "bar"); // self is a global variable  

在 PageMod 中,调用内容脚本的函数onAttach

/* main.js */
var self = require("sdk/self");
var pageMod = require("sdk/page-mod");

var externalStringVar =  "helloWorld";

var pageMod = pageMod.PageMod({
    include: "https://example.com/*",
    contentScriptWhen: "ready",
    contentScriptFile: [self.data.url("example.js")],
    contentScriptOptions: {
        myString: externalStrVar; // Pass it to the content script
    }
    onAttach: function(worker) {
        worker.port.on("nameForTheMessage", function(updatedString) {
            // update string value when a message is received like so:
            externalStringVar = updatedString;
        });
    }
});

MDN docs

【讨论】:

  • 我试过了,但是worker.port.on 函数中的myString 与传递给内容脚本的contentScriptOptions 中的myString 不同。它没有任何作用。
  • 我已经编辑了我的问题,以展示我目前所掌握的内容。
  • @iglvzx 我也更新了我的答案(注意两个文件都有变化)。
  • 现在 myString 数据没有传递给内容脚本。
  • @iglvzx 误会我深表歉意。包含contentScriptOptions 的新编辑应该可以帮助您从最简单的意义上实现您正在寻找的东西。还是您的意思是更新 contentScriptOptions 内部的 myString 的值?
【解决方案2】:

对选项的更新不会传播到已加载的工作人员。您必须使用通过port API 的消息传递来与内容脚本进行通信。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多