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

204
Visualizações
Chrome Extension - Obtaining Active Tab's DOM information through background script

I know there have been many questions related to this topic but none of them thus far have allowed me to figure this out in V3. When I run the following background.js, I only get undefined.

The goal of my extension, at least for this stage, is to scrape the active tab's DOM and extract the text content of all of the div elements.

My background.js page:

function getDOM() {
    let htmlarr = [];
    const pageDOM = document.getElementsByTagName('div');
    for (i = 0; i < pageDOM.length; i++) {
        htmlarr += pageDOM.innerHTML;
    }
    return Object.assign({}, htmlarr)
}

chrome.tabs.onActivated.addListener(activeInfo => {

    let domRes = chrome.scripting.executeScript({
        target: { tabId: activeInfo.tabId },
        func: getDOM
    })
    console.log(domRes);
});

my manifest.json:

    {
        "name": "HTML Sourcer",
        "description": "Extract HTML source code",
        "version": "1.0",
        "minimum_chrome_version": "10.0",
        "manifest_version": 3,
        "permissions": ["scripting", "tabs", "activeTab"],
        "host_permissions": [
            "*://*/*"
        ],
        "background": {
            "service_worker": "background.js"
        }
}

Any help would be much appreciated. Thank you!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Problem 1

Per the documentation this API method returns a Promise when there's no callback parameter.

To get the value of the Promise, add await and mark the function as async:

chrome.tabs.onActivated.addListener(async info => {

  let domRes = await chrome.scripting.executeScript({
    target: {tabId: info.tabId},
    func: getDOM,
  }).catch(console.error);
  if (!domRes) return;

  console.log(domRes);
});

There's a catch because some tabs don't support injection e.g. the start tab or chrome:// tabs.

Problem 2

In JavaScript += doesn't work with arrays, but only with numbers/strings. Use htmlarr.push() instead. There's also no need to convert the array to an object via Object.assign.

Actually, let's rewrite getDOM using Array.from:

function getDOM() {
  return Array.from(
    document.getElementsByTagName('div'),
    el => el.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