Puppeteer how to check if page is navigated and perform task if not navigated

Viewed 864

On the login page, I'm trying to figure out whether the google recaptcha appears or not. If it does, I want to run a block of code and otherwise navigate as usual.

await page.goto(
    url
  );
  await page.waitForSelector("#username");
  await page.type("#username", process.env.EMAIL);
  await page.type("#password", process.env.PSWD);
  await  page.$eval("#signIn > div > button", (el) => el.click()) //this line sometimes triggers recaptcha

  {//here wait for navigation and check if google captcha appears}

  //then run the following code:
  await page.solveRecaptchas();
  await Promise.all([
    page.waitForNavigation(),
    page.click("#signIn"),
  ]);

I've tried using page.waitForNavigation but it causes timeout if recaptcha appears. What can I do to run the bottom block of code ONLY if google recaptcha appears?

I also tried conditionally running the block of code on if recaptcha-token is present but I checked the dom and recaptcha element is always present and only prompts image select randomly. Basically I'm available to navigate sometimes without having to perform any captcha and sometimes i'm prompted with image select.

Thanks!

1 Answers

Maybe something like this?

const [_, navigation] = await Promise.allSettled([
  element.click(),
  page.waitForNavigation(),
]);

if (navigation.status === 'fulfilled') /* There was navigation. */;
else /* There was timeout, no navigation. */;
Related