如何获得点击链接的网址? [英] How to get the URL of clicked link?
问题描述
我知道这个过程涉及到通过一个page-mod添加一个eventlistener,然后使用tabs模块,但我似乎无法得到正确的语法。
$ b (这是我到目前为止)
var Widget = require(widget)。
var tabs = require('tabs');
var pageMod = require(page-mod);
$ b $ exports.main = function(){
pageMod.PageMod({
include:'*',
contentScriptWhen:'准备',
contentScript:window.addEventListener('click',function(event){self.port.emit('click',event.target.toString()),false),
onAttach:function(worker){
worker.port.on(click,function(urlClicked){
tabs.open(urlClicked);
});
}
});
};
我。但是,您的内容脚本代码有两个问题:
event.preventDefault() code>来阻止浏览器关注该链接。否则,链接的页面将被加载到当前选项卡和由您的扩展名打开的新选项卡中。
实际上是一个链接。它可能是链接的一个子节点,或者根本就不是链接。
总而言之,您的内容脚本应该看起来像这个:
window.addEventListener(click,function(event)
{
var link = event.target;
while(link& link.localName!=a)$ b $ link = link.parentNode;
if (链接)
{
self.port.emit(click,link.href);
event.preventDefault();
}
},false) ;
对于这样一个非平凡的内容脚本,你不应该使用 contentScript
参数,而是把它放到它自己的文件中的 data /
目录下。然后,您可以在构建面板时使用 contentScriptFile
参数:
$ b
contentScriptFile:require(self)。data.url(contentScript.js),
I am trying to create an add-on through Mozilla Add-On Builder. What I need to know is how to get the URL of a left clicked link in the active tab through the add-on and open it in a new tab.
I know this process involved adding an eventlistener through a page-mod and then using the tabs module, however I can't seem to get the syntax correct.
Edit: (This is what I have so far)
var Widget = require("widget").Widget;
var tabs = require('tabs');
var pageMod = require("page-mod");
exports.main = function() {
pageMod.PageMod({
include: '*',
contentScriptWhen: 'ready',
contentScript: "window.addEventListener('click', function(event) { self.port.emit( 'click',event.target.toString() )},false)",
onAttach: function(worker) {
worker.port.on("click", function(urlClicked) {
tabs.open(urlClicked);
});
}
});
};
The code you have there is mostly correct and works for me. There are two issues with your content script code however:
- It needs to call
event.preventDefault()
to prevent the browser from following the link. Otherwise the linked page will be loaded both in the current tab and the new tab opened by your extension. - It doesn't check whether
event.target
is actually a link. It could be a child node of the link or it might not be a link at all.
Altogether, your content script should look like this:
window.addEventListener("click", function(event)
{
var link = event.target;
while (link && link.localName != "a")
link = link.parentNode;
if (link)
{
self.port.emit("click", link.href);
event.preventDefault();
}
}, false);
For a non-trivial content script like this, you shouldn't use contentScript
parameter but rather put it into its own file in the data/
directory. You can then use contentScriptFile
parameter when constructing the panel:
contentScriptFile: require("self").data.url("contentScript.js"),
这篇关于如何获得点击链接的网址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!