What is the process to authenticate using Puppeteer?

I’m just starting with JavaScript and Puppeteer. I attempted the following login script, but it didn’t work properly. However, when I created newPage, the login was successful. What steps can I take to resolve this issue?

const USER_CREDENTIALS = require('./user_credentials');

async function run() {
  const puppeteer = require('puppeteer');
  const browserInstance = await puppeteer.launch({headless: false});

  const loginPage = await browserInstance.newPage();
  await loginPage.setViewport({width: 1200, height: 720});
  await loginPage.goto('https://www.example.com');
  await loginPage.waitForNavigation();
  await loginPage.type('#username', USER_CREDENTIALS.username);
  await loginPage.type('#password', USER_CREDENTIALS.password);
  await loginPage.click('#submit');

  const secondaryPage = await browserInstance.newPage();
  await secondaryPage.setViewport({width: 1200, height: 720});
  await secondaryPage.goto('https://example.org');
  await secondaryPage.type('#search', 'Puppeteer Automation');
}

run();

Hey, maybe try using waitForSelector after clicking the submit button before navigating to a new page. Sometimes, elements can take time to load due to network delay and waitForNavigation dindt handle it well. Adding a bit of wait time could help. Cheers!

It sounds like you might be timing out before the login process is fully completed. Besides using waitForSelector, you might want to leverage waitForNavigation after clicking the login button to ensure the page transition is complete. You could also consider using page.waitForNetworkIdle() which allows the script to act only after no more network connections are active within a specified period. This approach would take into account any AJAX calls or redirects that might occur after logging in.