Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
Get innerHTML via Chrome Extension

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>
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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);
})();
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda