How to get the URL of clicked link?

大憨熊 提交于 2019-12-13 01:18:51

问题


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);

        });
     }

    }); 

};

回答1:


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"),


来源:https://stackoverflow.com/questions/10326632/how-to-get-the-url-of-clicked-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!