Search code examples
javascriptnode.jscasperjspuppeteerheadless-browser

How can I pause and wait for user input with Puppeteer?


I need to make Puppeteer pause and wait for user input of username and password before continuing. It is a nodejs 8.12.0 app.

(async () => {
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();   
    await page.goto('https://www.myweb.com/login/');

    //code to wait for user to enter username and password, and click `login`

    const first_page = await page.content();

   //do something 

    await browser.close();
)}();

Basically the program is halted and waits until the user clicks the login button. Is it possible to do this in Puppeteer? Or what else can I do?


Solution

  • You can use page.waitForFunction() to wait for a function to return a truthy value before continuing.

    The following function will wait until the #username and #password fields contain a value before continuing:

    await page.waitForFunction(() => {
      const username = document.getElementById('username').value;
      const password = document.getElementById('password').value;
      
      return username.length !== 0 && password.length !== 0;
    });
    

    But since you are entering the #username and #password yourself, you can simply use:

    await page.type('#username', 'username');
    await page.type('#password', 'password');
    await page.click('#login');
    await page.waitForNavigation();