通过 Chrome 扩展获取 innerHTML

Get innerHTML via Chrome Extension

我想 fiddle 围绕 Chrome 扩展开发,我想我会制作一个简单的 v3 扩展,如果单击该图标,特定 html 元素的内容将被记录到控制台。但是,当我单击该图标时,我得到了 null.

我目前拥有的:

manifest.json

{
  "name": "Test Chrome Extension",
  "description": "Some test extension",
  "version": "1.0.0",
  "manifest_version": 3,
  "action": {
    "default_title": "Log the content of #someElement to the console"
  },
  "background": {
    "service_worker": "background.js"
  },
  "permissions": [
    "tabs",
    "scripting"
  ],
  "host_permissions": [
    "https://*/*",
    "http://*/*"
  ]
}

background.js

chrome.action.onClicked.addListener(execScript);

async function execScript() {

  const tabId = await getTabId();
  chrome.scripting.executeScript({
    target: {tabId: tabId},
    files: ['mycode.js']
  })
}

async function getTabId() {
  const tabs = await chrome.tabs.query({active: true, currentWindow: true});
  return (tabs.length > 0) ? tabs[0].id : null;
}

mycode.js

(function() {
  console.log('yes'); // this one works
  console.log(document.querySelector("#someElement").innerHTML); // this doesn't and returns null
})();

我尝试点击扩展图标的 html 页面包含以下内容:

<body>
  <!-- some html content -->
  <div id="someElement">
    <h2>Hello World</h2>
    <p>Lorem Ipsum text</p>
  </div>
  <!-- some html content -->
</body>

所以这只是因为 html 元素在 iframe 中。感谢@wOxxOm 在评论中指出这一点。

我通过将 mycode.js 更改为:

来修复它
(function() {
  const iframeElement = document.querySelector("#iframeId");
  const iframeCont = iframeElement.contentWindow || iframeElement.contentDocument;
  const iframeDoc = iframeContent.document ? iframeContent.document : iframeContent;
  console.log(iframeDoc.querySelector('#someElement').innerHTML);
})();