Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer wait for url

I have headless off and I want to wait untill user redirect to some page. I could use waitForRequest from puppeteer API but I don't know exact url it just must pass few circumstances.

So I use waitForFunction and check circumstances there but when I redirect to correct URL then I need to refresh page to pass circumstances for some reason.

My code is:

try {
    await page.waitForFunction(() => {
        if(window &&
           window.location &&
           window.location.hostname) {
            const host = window.location.hostname.split('.');
            if(!host.includes('www') &&
               !host.includes('new') &&
               host.includes('margonem') &&
               host.length === 3) {
                return true;
            }
        }
    }, {
        polling: 200,
        timeout: 0
    })
} catch (e) {
    console.log(e);
}

and when I redirect to URL which pass all of above if's then I need to reload page to actually see that it return true. Why it works like this? I don't want user to be forced to refresh page after he enter correct one.

like image 805
BT101 Avatar asked Oct 18 '19 12:10

BT101


3 Answers

I have headless off and I want to wait untill user redirect to some page.

just use waitForNavigation().

In combination with a click make sure you use this pattern:

const [response] = await Promise.all([
  page.waitForNavigation(waitOptions),
  page.click(selector, clickOptions),
]);

waitForNavigation also returns a response object that you can then inspect

I could use waitForRequest from puppeteer API but I don't know exact url it just must pass few circumstances.

in this case puppeteer injects the request as argument and you can just test this in your lambda function. For example:

page.waitForRequest(request => {
  return  request.url().includes('margonem') && request.method() === 'GET'
})
like image 131
B12Toaster Avatar answered Nov 12 '22 14:11

B12Toaster


The simplest way I have found is using waitForFunction, it is simple to modify to fit your specifications as well as compact.

  await page.waitForFunction("window.location.pathname == '/Welcome.aspx'")
like image 27
Asd20752 Avatar answered Nov 12 '22 14:11

Asd20752


Sometimes we need to wait until we reach a specific URL.

The best way to handle it is

    let holdProgress = true;
        while (holdProgress) {
            await page.waitFor(300);
            if (page.url().includes('/env-selector')) {
                holdProgress = false;
            }
        }

like image 26
Bhanuprakash Reddy Avatar answered Nov 12 '22 16:11

Bhanuprakash Reddy