Search code examples
google-chrome-devtoolspuppeteer

In puppeteer how to wait for DOM element to load and then click


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.


Solution

  • 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.
    })();