I am working on a chrome extension where I have to loop through an array of buttons to click.
Whenever a click on a connect button happens, a modal is appeared in the DOM to ask for a confirmation, and a send button needs to be clicked before moving on to the next button in the array.
The general flow is:
I am using mutationObserver() to wait for the modal to appear before firing off a click event on the Send button.
However, it only works once for the first element, and the loop stops.
Here's my code:
async function connect(): Promise<void> {
const connectBtn = document.querySelectorAll<HTMLElement>(
".connect"
);
const observer = new MutationObserver((mutations) => {
const send = document.querySelectorAll<HTMLElement>(
".send"
)[0];
if (send.textContent === "Send") {
send.click();
}
});
for (const btn of connectBtn) {
if (btn.textContent === "Connect") {
btn.click();
observer.observe(
document.querySelector("#modal") as HTMLElement,
{
childList: true,
subtree: true,
characterData: true,
}
);
}
}
observer.disconnect();
}