Javascript chrome.contextMenu如何获取html而不是字符串

Javascript chrome.contextMenu如何获取html而不是字符串,javascript,html,google-chrome-extension,Javascript,Html,Google Chrome Extension,我是chrome扩展的新手, 我正在创建一个基本扩展,它将在警报上显示所选的带有标记(span、divs和所有其他dom)的html 我尝试了这个chrome.contextMenus.create(下面的代码),但它只显示所选的字符串 chrome.contextMenus.create({title: "Selected HTML", contexts:["selection"], onclick: showSelectedHtml}); 我只是想知道是否有一种方法可以获得选中的HTMLD

我是chrome扩展的新手, 我正在创建一个基本扩展,它将在
警报上显示所选的带有标记(
span
divs
和所有其他
dom
)的html

我尝试了这个
chrome.contextMenus.create
(下面的代码),但它只显示所选的字符串

chrome.contextMenus.create({title: "Selected HTML", contexts:["selection"], onclick: showSelectedHtml});
我只是想知道是否有一种方法可以获得选中的HTMLDOM(如果有标签的话)而不是字符串

谢谢,

正如您在contextMenus API中看到的那样,API无法做到这一点

解决方案是运行一个内容脚本,获取HTML并将其返回到后台脚本中

manifest.json:

"permissions": ["activeTab", "contextMenus"],
"background": {
  "scripts": ["background.js"],
  "persistent": false
}
background.js:

// in Chrome the menus should be created only at install/update
chrome.runtime.onInstalled.addListener(() => {
  chrome.contextMenus.create({
    id: 'sel',
    title: 'Selected HTML',
    contexts: ['selection'],
  }, () => chrome.runtime.lastError); // ignore errors about an existing id
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
  chrome.tabs.executeScript(tab.id, {
    code: `(${getSelectedHtml})()`,
    frameId: info.frameId,
    matchAboutBlank: true,
    runAt: 'document_start',
  }, data => {
    if (chrome.runtime.lastError) {
      alert('Error: ' + chrome.runtime.lastError.message);
    } else {
      prompt('HTML', data[0]);
    }
  });
});
// this function's code will be executed as a content script in the web page
function getSelectedHtml() {
  const sel = getSelection();
  let html;
  if (sel.rangeCount) {
    const div = document.createElement('div');
    div.appendChild(sel.getRangeAt(0).cloneContents());
    html = div.innerHTML;
  }
  return html || '';
}
注意:不要在contextMenus.create()中使用
onclick
属性,因为它不适用于
“persistent”:false
后台脚本,后者是首选类型()