首先,你的附加住在一个不同的,更多的特权环境中比在页面代码的代码 - 在不远的未来,他们会还有两个不同的过程 - 所以你没有交流直接访问该页面:您必须使用content script。我建议你仔细阅读链接的页面,因为它会向你提供他们如何相互沟通。
说的是,我的想法是:当用户点击一个按钮时,将内容脚本附加到当前页面(如果还没有的话)。在内容脚本中,听取点击事件,并做你的东西。
这里的例子为您main.js
const { ActionButton } = require("sdk/ui/button/action");
const { data } = require("sdk/self")
const tabs = require('sdk/tabs');
let button = ActionButton({
id: "fieldResolver",
label: "Field Resolver",
icon: {
"16": "./icon-16.png",
"32": "./icon-32.png",
"64": "./icon-64.png"
},
onClick: handleClick
});
function handleClick() {
// get the current tab
let tab = tabs.activeTab;
// you would probably want to store worker somewhere to be sure
// that you won't attach more than once
let worker = tab.attach({
contentScriptFile: data.url("content.js")
});
}
正如你所看到的,你需要一个contentScriptFile
,即必须是在你的附加组件的数据文件夹。 你content.js
意志的样子:
function clickHandler (event) {
// do something with the element clicked
console.log(event.target.outerHTML);
}
window.addEventListener("click", clickHandler);
// We want to clean the page if the worker is destroyed
self.port.on("detach", function() {
window.removeEventListener("click", clickHandler);
})
可以卸下工作人员打电话worker.destroy()
随时随地。正如我所说的,您可能需要将worker
存储在某个地方,例如Map,以便只有在没有任何工作人员的情况下才会附加该脚本。