Using Javacript, Button element properly selected but .click() happening though event successfully triggered

26 Views Asked by At

I am doing a Javascript userscript that can click on 'Voir plus' automatically on this webpage. To select the button element 'Voir plus' I am using the great waitForElem function. This work great "console.log('Element is ready: ' + elm.textContent);" gives "Element is ready: Voir plus" but the click on 'Voir plus' does not happen, though I can see this in the console 'Click event triggered successfully.' (and adding a setTimeout on elm.click() does not help).

function waitForElm(selector) {
    return new Promise(resolve => {
        if (document.querySelector(selector)) {
            return resolve(document.querySelector(selector));
        }

        const observer = new MutationObserver(mutations => {
            if (document.querySelector(selector)) {
                observer.disconnect();
                resolve(document.querySelector(selector));
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    });
}

waitForElm('div[data-qa-id="adview_description_container"] > button').then((elm) => {
    if (elm) {
        console.log('Element is ready: ' + elm.textContent);
        try {
            elm.click();
            console.log('Click event triggered successfully.');
        } catch (error) {
            console.error('Error while clicking the element:', error);
        }
    } else {
        console.error('Element not found.');
    }
}).catch((error) => {
    console.error('Error while waiting for the element:', error);
});
0

There are 0 best solutions below