Reputation: 2022
In puppeteer how to wait for DOM element to load and then click. I am trying access a simple page, hit the Start button and then a text field should appear, and I need to type in that text field.
Code given as below.
const puppeteer = require('puppeteer');
const sleep = (waitTimeInMs) => new Promise(resolve => setTimeout(resolve, waitTimeInMs));
(async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto('https://janus.conf.meetecho.com/videocalltest.html');
await page.click('#start', {waitUntil: 'domcontentloaded'});
//await sleep(5000);
await page.type('#username', 'austin');
await sleep(5000);
await browser.close();
})();
However if I put a sleep of 5 second (commented in above code), then I am able to type in text field.
I want to avoid giving sleep. Please suggest what's the work around.
Upvotes: 3
Views: 2293
Reputation: 8672
You need to wait for the element to be visible because the element is present in the DOM, but not visible.
Here is the script that works:
(async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto('https://janus.conf.meetecho.com/videocalltest.html');
await page.click('#start');
await page.waitForSelector('#username', { visible: true });
await page.type('#username', 'austin');
// await browser.close(); // commented it just to make sure that text is typed in the input before close browser.
})();
Upvotes: 4
Reputation: 135
//Errors
await page.waitForSelector('#username', {visible: true})
.then(()=>{
console.log('success');
})
.catch((err)=>{
console.log(err);
}
Upvotes: 0
Reputation: 3670
You can use ;page.waitForSelector(selector[, options])
:
await page.waitForSelector('#username', {visible: true})
Upvotes: 3