Reputation: 508
I am adding content scripts to pages on example.com
using the following code in my 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: 'helloWorld'
}
});
If I set up a worker or event listener that tells main.js
to update the value of myString
(accessible from the content script using self.options.myString
), how can I reflect that change in the example.js
content script for the next example.com
page load?
I've tried calling the pageMod.PageMod
function again with the new myString
value, but that causes example.js
to run twice on pages.
Edit:
I've implemented the Port API, but now I'm stuck on how to update the object that contentScriptOptions
passes to the content scripts.
/* 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?
});
}
});
and
/* example.js */
self.port.emit('updateOptions', { myString: 'bar' });
Upvotes: 1
Views: 278
Reputation: 3570
You need the Port API.
In your content script, emit
the message that a listening PageMod will receive.
/* example.js */
self.port.emit("nameForTheMessage", "bar"); // self is a global variable
In the PageMod, invoke a function onAttach
of the content script.
/* 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;
});
}
});
Upvotes: 1