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!
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.
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
);
}