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 therequire
function. There is no globalWorker
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 toa tab
any page that matches an array of URLs or regex, using a
PageMod
an invisible background page with
PageWorker
, which is probably what you're going forNote that
panel
s work very similarly toworker
s in that they haveonMessage
andport
attributes.Note also that
onMessage
is spelt with a capitalM
In Firefox Addon, use ChromeWorker instead of worker.
Add the following lines in main.js
my_worker.js
put your my_worker.js file in data/ directory.