I'm new to puppeteer and I try to convert this javascript code :
let messageElement;
await driver.findElements(By.className("message-list-item")).then(
(ok) => {
messageElement = ok.pop()
}
)
await messageElement.getAttribute("id").then(
(ok) => {
messageNum = parseInt(ok.split("message")[1]);
}
)
The ".pop()" method need to be convert and I know with puppeteer we can use "length - 1" but I can't. I've tried this :
const el = await page.$('.message-list-item')
.then( (elements) => elements[el.length - 1]);
But not work.
This has nothing to do with "converting .pop() to puppeteer". pop is a standard function on the Array prototype. According to the puppeteer docs, the page.$(<selector>) performs a querySelector on the DOM nodes, which returns the DOM node directly rather than an array of DOM nodes, so you don't need to use pop or any other Array function.
const el = await page.$('.message-list-item')
.then( (element) => element));
which is equivalent to
const el = await page.$('.message-list-item');
EDIT
If you want the last element with that classname, then you need to get a list of those items, for which you can use $$ which according to the docs uses querySelectorAll, and then get the last element.
const el = await page.$$('.message-list-item', (e) => e[e.length - 1]);
With :
const h4All = await page.$$('.message-list-item');
const h4Count = h4All.length;
const fileName = h4All[h4Count - 1];
const id= await (await fileName.getProperty("id")).jsonValue();
console.log(await id);
messageNum = parseInt(id.split("message")[1]);
console.log(messageNum);
It's work, thanks for your help ! Can I ask you another problem ? I've this javascript :
let messageNum = 0;
let lastMessageElement
let y = false;
while(!y){
console.log("Message de recherche " + messageNum);
await driver.findElement(By.id("message"+messageNum.toString())).then(
(ok) => {
console.log("Trouvé");
y = true;
lastMessageElement = ok;
},
(error) => {
console.log("Error");
}
)
if(!y) await driver.sleep(5000);
}
Try to convert in puppeteer:
let messageNum = 0;
let lastMessageElement
let y = false;
while(!y){
console.log("Message de recherche " + messageNum);
const lastMessageElement = await page.$$("message"+messageNum.toString());
console.log(lastMessageElement);
if (lastMessageElement)
{
console.log("Trouvé");
console.log(lastMessageElement);
y = true;
}
else {
console.log("Error");
}
if(!y) await page.waitForTimeout(5000);
}
But it's not good ... Thanks again