I'm creating an incredibly simple Firefox extension. I used cfx init
to create the directory structure and have code in lib/main.js
and data/my_worker.js
main.js
is as follows:
var worker = new Worker("my_worker.js");
worker.onmessage = function(e) {
console.log(e.data);
};
worker.postMessage("Bobby");
and my_worker.js
is as follows:
self.onmessage = function(e) {
self.postMessage("Hello " + e.data);
};
Then I run: cfx run
to run the extension. The results are as follows:
(addon-sdk-1.17)me:lib me$ cfx run Using binary at
'/Applications/Firefox.app/Contents/MacOS/firefox-bin'. Using profile
at
'/var/folders/p1/zzdzcrrx6pq96hgsmy5xjqmh0000gp/T/tmp57OYe9.mozrunner'.
console.error: test: Message: ReferenceError: Worker is not defined
Stack:
@resource://jid1-zmowxggdley0aa-at-jetpack/test/lib/main.js:1:9 CuddlefishLoader/options<.load@resource://gre/modules/commonjs/sdk/loader/cuddlefish.js:129:18
run@resource://gre/modules/commonjs/sdk/addon/runner.js:138:19
startup/
I tried putting my_worker.js
in both the data
and lib
folders but neither works. This seems like a SUPER simple extension. What could be going wrong?
It's probably a good idea to read some intro docs before starting to code.
The Firefox add-on SDK uses modules that need to be imported into main.js
using the require
function. There is no global Worker
object, as the error is pretty explicit about. A content script needs to be attached to an HTML page somewhere; it can't exist alone. The three most common ways to get a worker are by attaching a content script to
a tab
var tabs = require("sdk/tabs");
tabs.on('ready', function(tab) {
var worker = tab.attach({
contentScript:
'document.body.style.border = "5px solid red";'
});
});
any page that matches an array of URLs or regex, using a PageMod
var tag = "p";
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: "*.mozilla.org",
contentScriptFile: data.url("element-getter.js"),
onAttach: function(worker) {
worker.port.emit("getElements", tag);
worker.port.on("gotElement", function(elementContent) {
console.log(elementContent);
});
}
});
an invisible background page with PageWorker
, which is probably what you're going for
pageWorker = require("sdk/page-worker").Page({
contentScript: "console.log(document.body.innerHTML);",
contentURL: "http://en.wikipedia.org/wiki/Internet"
});
Note that panel
s work very similarly to worker
s in that they have onMessage
and port
attributes.
Note also that onMessage
is spelt with a capital M
In Firefox Addon, use ChromeWorker instead of worker.
Add the following lines in main.js
var { ChromeWorker } = require("chrome");
var self = require("sdk/self");
var data = self.data;
var localWorker = new ChromeWorker(data.url("my_worker.js"));
worker.onmessage = function(e) {
console.log(e.data);
};
worker.postMessage("Bobby");
my_worker.js
self.onmessage = function(e) {
self.postMessage("Hello " + e.data);
};
put your my_worker.js file in data/ directory.