在Chrome扩展上下文菜单中获取选择DOM

hivapdat  于 11个月前  发布在  Go
关注(0)|答案(3)|浏览(112)

我尝试在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扩展contextMenu中获得选择DOM吗?。请建议。谢谢。

wa7juj8i

wa7juj8i1#

要访问所选内容,您需要将content script注入页面。
在那里,您可以调用getSelection()来获取Selection object,并在其中使用范围来提取所需的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


你可能想看看Messaging docs

qkf9rpyu

qkf9rpyu2#

如果你只想从上下文菜单中选择文本,那么你可以通过下面的代码来实现。

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

字符串

dauxcl2d

dauxcl2d3#

我是如何在v3 manifest中解决它的:

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权限。

相关问题