2014-07-15 45 views
0

我想为页面中的所有html元素分配点击处理程序。但用户点击我的插件按钮,而不是在页面加载。向所有元素添加点击事件侦听器 - Firefox插件

以下是出发点。我无法设法分配全局点击处理程序。 有什么想法?谢谢。

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:$没有定义 无论是文档对象是不可用

回答

1

首先,你的附加住在一个不同的,更多的特权环境中比在页面代码的代码 - 在不远的未来,他们会还有两个不同的过程 - 所以你没有交流直接访问该页面:您必须使用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,以便只有在没有任何工作人员的情况下才会附加该脚本。

0

添加点击监听器窗口,然后检查event.target

function handleClick() { 
    //try using jquery here. if $ doesnt work try window.$ 
    window.addEventListener('click', intercept, false); 
} 

function intercept(e) { 
    //try using jquery here. if $ doesnt work try window.$ or try e.target.ownerDocument.defaultView.$ 
    var elementClicked = e.target; 
    console.log('elementClicked = ', elementClicked); 
    elementClicked.style.border = '1px solid red'; 
} 
相关问题