Monday, October 25, 2021

Puppeteer page waitForSelector and visible:true option won't process click

I had a problem in Puppeteer where an initially hidden menu has to be invoked by clicking on the menu icon. I used await page.waitForSelector(selector) and then called page.click(selector), where 'selector' is a css selector and page is my page object in Puppeteer. Nothing happened. I figured that as the page had just loaded the menu icon might have been in the DOM but not yet visible. So I tried adding the visible:true option: page.waitForSelector(selector,{visible:true}). Again nothing happened. Then I added a short delay before page.click(selector) via page.waitForTimeout(2000) and it worked. But that's like a hack. I mean how long do you wait? So I figured that the menu icon is visible but the click-handler for it is not yet loaded, and waiting ensures that it usually is. But how to do it correctly? Then I tried this:

await page.waitForSelector(selector);
await page.$eval(selector, elem => elem.click());

And it worked.

No comments:

Post a Comment