I have just started to use Google Chrome's console to play around with websites. I don't know JavaScript, but I am a novice programmer (currently learning C++). I'm trying to put together code that will select html elements on a web page and click them. I got most of the code to work the way I want, but I am finding out that $x() does not work the way I thought it did. After the code runs through the outer for() loop once, it stops and I get an error, "VM44269:8 Uncaught (in promise) ReferenceError: $x is not defined". Are there any alternatives to $x() that will work with the code below? Also, how would I use it to find the elements with the attribute: aria-label="Message not selected,, checkbox, unchecked."? If I need to provide other details, please let me know. Thanks in advance to anyone who can help me with this.
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function clickButtons() {
for (var i = 0; i < 5; i++)
{
arr = $x('.//*[contains(@aria-label, "Message not selected,, checkbox, unchecked.")]');
for (var j = arr.length - 1; j >= 0; j--){
arr[j].scrollIntoView({
behavior: 'smooth'
});
await sleep(200);
arr[j].click();
}
}
}
From the suggestions I assembled a working solution.
function sleep(ms) // our sleep function to wait for webpage elements to load
{
return new Promise(resolve => setTimeout(resolve, ms));
}
function getElementsByXPath(xpath, parent) // get an array of elements with desired xpath
{
let results = [];
let query = document.evaluate(xpath, parent || document,
null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (let i = 0, length = query.snapshotLength; i < length; ++i) {
results.push(query.snapshotItem(i));
}
return results;
}
async function clickButtons()
{
var arr = getElementsByXPath('//*[contains(@aria-label, "Message not selected,, checkbox, unchecked.")]'); // find message buttons
while (arr.length >= 1) // if array is empty then exit
{
for (var j = arr.length - 1; j >= 0; j--) {
arr[j].scrollIntoView({ behavior: 'smooth' }); // scroll to element
await sleep(200); // sleep to allow loading; may need to be increased
arr[j].click(); // click on button elements
}
arr = getElementsByXPath('//*[contains(@aria-label, "Message not selected,, checkbox, unchecked.")]');
}
}
clickButtons(); // execute our code