Add-on Builder: ContentScript and back to addon code?
I am using Firefox Add-on Builder and this 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 am stuck on how to get the url variable back to main.js so that it can open the url in a new tab. From myScript.js, I have no access to the tabs object declared in main.js.
+3
source to share
1 answer
Sure! The attach method returns a working instance that you can use to customize your 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});
See the docs for the attach method for more on this:
... as well as a guide to content scripting:
Caveat: Don't run this code, but it should work.
+1
source to share