Puppeteer flow logic, check if navigation has occurred (vs wait for)

Viewed 556

Looking for some feedback. In Puppeteer, I want to check if navigation has occurred, do something if it has, else do something else if it hasn't (e.g. try again). The two ways of doing it I've come up with are:

if (await page.url() != finalURL) {
    let t = 0;  
    busy: while(t > 400) {
        try {
            await Promise.all([
                await page.click('#tryAgainLink'),
                await page.waitForNavigation(),
            ]);
            break busy;
        } catch(err) {
            // navigation didn't happen
            t++;
            await page.waitForTimeout(1500);
        }
    }
}

However my understanding is that it's not ideal to try/catch for flow logic. My alternative is something like this:

let t = 0;
busy: while(await page.url() != finalURL) {
    await page.click('#tryAgainLink');
    await page.waitForTimeout(1500);
    t++;
    if(t > 400) {
        break busy;
    }
}

I wonder if I should have a waitForNavigatin in there, but again would have to catch the thrown error if it hasn't. I mean to test this, but I am not sure if that await page.url() for the while loop will fire a couple of times while a navigation is occurring, and/or if that will break the page context.

Is there a better way than the above two methods? The first one does work, and I am tempted to leave it as is. Thank you.

3 Answers

You should be able to do something like:

await page.waitForFunction((finalUrl) => {
  return document.location === finalUrl
}, {}, finalUrl).catch(retry)

but it might be simpler to just:

await page.waitForResponse(finalUrl).catch(retry)

Maybe something like this:

if (page.url() !== finalURL) { // await is not needed here
    let t = 0;
    busy: while(t < 400) { // was '> 400' a typo?
        const [_, navigation] = await Promise.allSettled([
            page.click('#tryAgainLink'),
            page.waitForNavigation(),
        ]);

        if (navigation.status === 'fulfilled') break busy;

        t++;
        await page.waitForTimeout(1500);
    }
}

I use this approach:


async function isNavigation() {
  try {
    await page.evaluate(() => console.log('any code'))
    return false
  } catch (ex) {
    // check error, should be:
    // "Execution context was destroyed, most likely because of a navigation"
    return true
  }

}

Related