'How to fetch data from DOM, process it and then send it back in Chrome Extension MV3
I don't know what's the best way to phrase it, but I decided to make a post here since I've been searching for a few days and couldn't find an exact answer to what I want to do.
So, basically I'm trying to develop a simple Chrome extension to check if users on Reddit are bots or not. The extension would:
- Fetch all users from the current thread using document.querySelectorAll;
- Fetch user personal data from reddit;
- Check which users are bots;
- Append a [BOT] tag to all bots identified.
At first I tried to do something like this in my background.js:
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete'){
chrome.scripting.executeScript({
target: { tabId: tabId},
func: getAuthors,
},
(authors) =>{
authors.forEach(element => {
getAbout(element).then(about =>{
getComments(element).then(comments =>{
isBot(about,comments).then(response =>{
//ADD TAG
});
});
});
});
})
}
});
The function getAuthors is able to sucessfully access the document and retrieve the data, the problem happens when I have to access it again to append the tags.
Storing an array of authors and passing it in another chrome.scripting.executeScript doesn't work, since the execution won't wait for the first chrome.scripting.executeScript to finish and will execute it immediately.
I've tried inverting the logic and use messaging as well, this time in my contentScript.js:
chrome.runtime.sendMessage('get-names', (names) => {
console.log('received user data', names);
names.forEach(element => {
element.parentElement.appendChild(tag);
});
});
Now I have a way to append the tags, but I can't send the data to process it in the first place, since, as far as I know, you can only send a payload on response. if I send a message from my background.js instead, I end up falling in a similar situation with the scripting and its asynchronous execution.
Is there an easy way to do this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
