gpt4 book ai didi

javascript - 向所有元素添加单击事件监听器 - Firefox 插件

转载 作者:行者123 更新时间:2023-12-02 17:11:52 24 4
gpt4 key购买 nike

我想为页面中的所有 html 元素分配一个点击处理程序。但在用户单击我的插件按钮后,而不是在页面加载时。

下面是起点。我无法分配全局点击处理程序。有任何想法吗??谢谢。

var buttons = require('sdk/ui/button/action');

var button = buttons.ActionButton({
id: "fieldResolver",
label: "Field Resolver",
icon: {
"16": "./icon-16.png",
"32": "./icon-32.png",
"64": "./icon-64.png"
},
onClick: handleClick
});

function handleClick() {

}

当我使用 jquery 时,我收到此错误,因此 jquery 不是一个选项:消息:ReferenceError:$未定义任一文档对象都不可用

最佳答案

首先,您的附加组件的代码与页面代码相比处于不同的、更特权的上下文中 – 在不久的将来,它们也将是两个不同的进程 – 所以您无权访问直接进入页面:您必须使用 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 ,以便仅当该选项卡/网址没有任何工作程序时才附加脚本。

关于javascript - 向所有元素添加单击事件监听器 - Firefox 插件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24754177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com