Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!