I'm using the Firefox Add-on Builder and here is what I have so far:
main.js:
var widgets = require("widget");
var tabs = require("tabs");
var data = require("self").data;
var widget = widgets.Widget({
id: "div-show",
label: "Show divs",
contentURL: "http://www.mozilla.org/favicon.ico",
onClick: function() {
tabs.activeTab.attach({
contentScriptFile: [data.url("jquery.js"), data.url("myScript.js")]
});
}
});
myScript.js
var first = $(".avatar:first");
var url = first.attr("href");
Now I'm stuck on how to have the url variable passed back to main.js so it can open the url in a new tab. From myScript.js I don't have access to the tabs object declared in main.js.
Sure! The attach method returns a worker instance that you can use to set up an event handler:
// main.js
var widgets = require("widget");
var tabs = require("tabs");
var data = require("self").data;
var widget = widgets.Widget({
id: "div-show",
label: "Show divs",
contentURL: "http://www.mozilla.org/favicon.ico",
onClick: function() {
var worker = tabs.activeTab.attach({
contentScriptFile: [data.url("jquery.js"), data.url("myScript.js")]
});
worker.port.on('got-url', function(data) {
tabs.open(data.url);
});
}
});
// myScript.js script:
var first = $(".avatar:first");
var url = first.attr("href");
self.port.emit('got-url', {url: url});
For more on this, see the docs for the attach method:
https://addons.mozilla.org/en-US/developers/docs/sdk/1.5/packages/addon-kit/docs/tabs.html#attach%28options%29
...as well as the content scripts guide:
https://addons.mozilla.org/en-US/developers/docs/sdk/1.5/dev-guide/addon-development/web-content.html
Caveat: haven't run this code, but it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With