Home > Software engineering >  Get innerHTML via Chrome Extension
Get innerHTML via Chrome Extension

Time:12-30

I wanted to fiddle around with Chrome Extension development and thought I would make a simple v3 Extension where if the icon is clicked, the content of a particular html element will be logged to the console. However, when I click the icon, I got null.

What I have so far:

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

And the html page that I tried to click the extension icon on has the following content:

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

CodePudding user response:

So it was simply because the html element was inside an iframe. Thanks to @wOxxOm for pointing that out in the comments.

I fixed it by changing mycode.js to:

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