Firefox插件:在选择后将值从上下文菜单传递给contentScriptFile

Firefox add-on : passing value from context menu to contentScriptFile after selection

本文关键字:菜单 上下文 contentScriptFile 插件 选择 Firefox      更新时间:2023-09-26

我正在开发一个插件,当用户选择一个值并右键单击上下文菜单..该对象的属性必须存储。

下面是我的代码

Main.js

var contextMenu = require("sdk/context-menu");
var menuItem = contextMenu.Item({
  label: "Log Selection",
  context: contextMenu.SelectionContext(),
  contentScript: 'self.on("click", function () {' +
                 '  var text = window.getSelection().toString();' +
                 '  self.postMessage(text);' +
                 '});',
  accessKey: "l",
  onMessage: function (selectionText) {
    console.log(selectionText);
    contentScriptFile: [data.url("test.js")]
    }
});

下面是test.js,我想取selectiontext对象并打印其innerhtml

. js

parseElement(document.getElementById("selectionText"));
function parseElement(Element)
{
  if (Element == null)
    return;
alert(Element.innerHTML);

以下是我面临的一些问题,请帮助我

  1. 我无法理解如何获得选择文本的属性,如inspect element

  2. 如何将选定的文本属性传递给main.js

您的data.js中的函数称为parseElement。但是,一个选择可以包含元素的一部分或多个元素,每个元素都可以有自己的HTML标记和CSS属性。其实挺复杂的。

在内容脚本中,document.getSelection()将返回一个Selection对象。这个Selection包含了document.getSelection().rangeCount给出的一些Range。第一个范围(除非您使用ctrl键选择了多个范围,否则不会有多个范围)由document.getSelection().getRangeAt(0)给出。对于这个答案的其余部分,我将假设Selection中只有一个范围,它应该涵盖绝大多数用例。下面的表达式表示单范围选择:

var selection = document.getSelection();
var range = selection.getRangeAt(0);

不幸的是,(据我所知)没有一种快速而肮脏的方法来获取与该范围关联的所有HTML元素的列表。Range类确实有一个属性,它给出了共同祖先,这是最小的Node,它包含了全部或部分被Range包含的所有元素:

var ancestorContainer = range.commonAncestorContainer;
顺便说一下,所有HTML元素都由Node s表示。并非所有的Node都是元素。其中,.nodeType属性的值为Node.ELEMENT_NODE。最多有两个节点部分位于Range内。这些是range.startContainerrange.endContainer。对于(1)完全在选择范围内并且(2)是元素的节点,NodeIterator可能是获得它们的确定列表的最直接的方法:
var nodeIterator = document.createNodeIterator(
  // first argument is the root node at which to begin the NodeIterator's traversal:
 ancestorContainer,
 // second argument 'whatToShow'; we're interested in elements:
 NodeFilter.SHOW_ELEMENT,
 // third argument 'filter', a function whose return value tells iterator which nodes to iterate over.
 function (node) {
  return selection.containsNode(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
 }
);

然后从NodeIterator中获得实际的Node s(在本例中是Element s):

var elementsWithinSelection = [];
var e = nodeIterator.nextNode();
while (e) {
 elementsWithinSelection.push(e);
 e = nodeIterator.nextNode();
}

对于每个Element的属性,它们的.tagName, .textContent.style属性应该包含您需要的信息。将信息发送到您编写为onMessage属性的函数是使用self.postMessage(string)的问题。一个例子可能是:

self.postMessage(JSON.stringify(elementsWithinSelection.map(function (e) {
 return e.outerHTML;
})));