Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

203
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda