Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 988
Davis Avatar asked Sep 17 '25 02:09

Davis


1 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)
like image 62
pguardiario Avatar answered Sep 19 '25 17:09

pguardiario