简体   繁体   English

在新标签页中打开页面上的所有链接并跟踪这些标签页

[英]Open all links on page in new tabs and track those tabs

I know I cannot directly access the DOM from the main function in a firefox addon with the SDK, and therefore I cannot obtain the href values from the a tags directly either. 我知道我无法使用SDK通过firefox插件的main函数直接访问DOM,因此也无法直接从a标签获取href值。 How can I make my addon open all of the links on a page as new tabs and add those to an array? 如何使插件将页面上的所有链接作为新选项卡打开并将其添加到数组中? I don't want new tabs manually opened by the user to be tracked, just the ones created by this addon. 我不想跟踪用户手动打开的新选项卡,而只是跟踪此插件创建的选项卡。

Partially solved the issue a while back so I figure I'll point out what I know. 不久前部分解决了该问题,因此我想指出一点。

Since the main script can't access the DOM itself, it can instead attach a worker to the current tab. 由于主脚本无法访问DOM本身,因此可以将辅助线程附加到当前选项卡。 The worker can read all of the links and store them as a list, then send that list back to the add-on. 工作人员可以阅读所有链接并将其存储为列表,然后将该列表发送回附加组件。 The add-on can then open new tabs directed at all the links in that list. 然后,该附件可以打开指向该列表中所有链接的新选项卡。

In main, add a content script to the tab: 在main中,将一个内容脚本添加到选项卡:

function attachScript() {
  var worker = tabs.activeTab.attach({
    contentScriptFile: self.data.url("content-script.js")
  });
  worker.port.on("links", function(links) {
    for each(var l in links) {
        tabs.open(l);
    }
  }); // Start listening for links sent by the tab's worker
  worker.port.emit("get-links"); // Request links from worker
}

In the content script, upon receiving a get-links message, read all the links and send them back using port: 在内容脚本中,收到一条get-links消息后,读取所有链接并使用端口将其发送回:

self.port.on("get-links", handleMessage); // Start listening for requests for links on page

function handleMessage(message) {
  var anchors = document.getElementsByTagName("a"); // Get all a elements on page
  alert(anchors.length); // Report quantity of a elements found
  var hrefs = [];
  for each (var a in anchors) {
    hrefs.push(a.href); // Add all target urls of a elements to array
  }
  self.port.emit("links", hrefs); // Send array of urls to add-on script
}

As for tracking the tabs, I imagine keeping a list of the workers would be the appropriate way to accomplish this. 至于跟踪选项卡,我想保留一份工人名单是完成此任务的适当方法。 I haven't tried that part yet as I had to put this project down for a while. 我还没有尝试过那部分,因为我不得不将这个项目放下一段时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM