I want to loop through an array of URLs and click a "follow" button on each page with a Chrome extension in JavaScript. Right now the script loops through every page and waits for the follow button, but it does not click it.
The background script should loop through all of the pages. Then, it should stop looping and inject some JavaScript code in the website that checks if there's an unfollow button with Mutation Observer. If that's the case, the loop should continue and go to the next page. If there's a follow button, the button should be clicked before going to the next page.
Background.js:
const list = ["https://www.twitch.tv/hello1", "https://www.twitch.tv/hello2"];
// When the start button is clicked
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.start === true) {
// Loop through every link
(async () => {
for (const link of list) {
await new Promise((resolve) => {
chrome.tabs.update({ url: link }, (tab) => {
chrome.tabs.onUpdated.addListener(function onUpdated(tabId, info) {
chrome.tabs.onUpdated.removeListener(onUpdated);
chrome.scripting.executeScript(
{
target: { tabId: tab.id },
files: ["follow.js"],
},
() => {
resolve();
}
);
});
});
});
}
})();
}
});
follow.js:
function clickFollow() {
document.querySelector("button[data-a-target='follow-button']").click();
}
function waitForElement(timeout) {
return new Promise((resolve, reject) => {
var timer = false;
const observer = new MutationObserver(() => {
if (document.querySelector("button[data-a-target='follow-button']").length) {
if (timer !== false) clearTimeout(timer);
return resolve();
}
if (document.querySelector("button[data-a-target='unfollow-button']").length) {
observer.disconnect();
if (timer !== false) clearTimeout(timer);
setTimeout(clickFollow, 1000);
}
});
observer.observe(document.body, {
childList: true,
subtree: true,
});
if (timeout)
timer = setTimeout(() => {
observer.disconnect();
reject();
}, timeout);
});
}
waitForElement(5000);