在Chrome扩展程序右键菜单中获取选项的DOM

4

我尝试通过Chrome扩展中的ContextMenu获取所选DOM。

代码:

chrome.contextMenus.onClicked.addListener(function(info, tab){
  // the info.selectionText just the text, don not contains html.
});

chrome.contextMenus.create({
  title: "Demo",
  contexts: ["selection"],
  id: "demo"
});

但是info.selectionText中不包含HTML DOM信息。有没有办法在Chrome扩展程序的上下文菜单中获取选定的DOM?请给出建议。谢谢。


可能是获取包括HTML在内的页面选择?的重复问题。 - Zach Saucier
3个回答

6
要访问选择内容,您需要将内容脚本注入页面。
在那里,您可以调用getSelection()以获取Selection对象并在其中使用范围来提取所需的DOM。
// "activeTab" permission is sufficient for this:
chrome.contextMenus.onClicked.addListener(function(info, tab){
  chrome.tabs.executeScript(tab.id, {file: "getDOM.js"})
});

getDOM.js:

var selection = document.getSelection();
// extract the information you need
// if needed, return it to the main script with messaging

您可能想查看消息文档


0
如果您只想从上下文菜单中选择文本,则可以按照以下代码进行操作。
function getClickHandler() {
    return function(info, tab) {
      // info.selectionText contain selected text when right clicking
      console.log(info.selectionText);
    };
  };


/**
 * Create a context menu which will only when text is selected.
 */
chrome.contextMenus.create({
  "title" : "Get Text!",
  "type" : "normal",
  "contexts" : ["selection"],
  "onclick" : getClickHandler()
});

1
如果我想获取被点击的DOM,我该如何更改代码使其工作? - Gideon Babu
@Gideon 我认为你应该尝试记录通过getClickHandler()传递的“info”变量。 - Hitesh Chavda

0
在v3清单中,我是如何解决这个问题的:
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
  const tabId = tab?.id;

  if (tabId && info.menuItemId === 'my menu item' && info.selectionText) {
    chrome.scripting.executeScript(
      {
        func: () => {
          const selection = window.getSelection();
          const range = selection?.getRangeAt(0);
          if (range) {
            const clonedSelection = range.cloneContents();
            const div = document.createElement('div');
            div.appendChild(clonedSelection);
            return div.innerHTML;
          }
        },
        target: {
          tabId,
        },
      },
      (result) => {
        const html = result[0].result;
        // do something with `html`
      },
    );
  }
});

这需要同时具备scriptingactiveTab权限。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接