Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function similar to document.ready() in Puppeteer?

Is there something like document.ready() in Puppeteer?

There is:

page.waitForSelector(selector)

Since there are so many same-name selector on any HTML page, how can this function can be sure that the right page has been loaded? It is a simple function, but caused quite a few errors when I use it before page.content(). I'm not sure what is missed about this function.

like image 969
user938363 Avatar asked Oct 27 '18 00:10

user938363


People also ask

What does Page waitForNavigation do?

It fills the login form, submits the login form, waits for the form to be submited and then redirects to dashboard. On the server it works fine if I remove await page. waitForNavigation(); from the code and I get redirected to dashboard.

How do you make a puppeteer wait?

You can use Puppeteer's page. waitForNavigation() method here to explicitly wait for this event to happen and then continue your script. The accepted notation in Puppeteer's case is by using the Promise. all() method to wait for the click to happen and the navigation to happen before continuing.

What is DOM ready in Javascript?

DOM ready means that all the HTML has been received and parsed by the browser into the DOM tree which can now be manipulated. It occurs before the page has been fully rendered (as external resources may have not yet fully downloaded - including images, CSS, JavaScript and any other linked resources).


2 Answers

You can use page.waitForNavigation() as an alternative to jQuery's document.ready() function:

await page.waitForNavigation({waitUntil: 'load'});             // consider navigation to be finished when the load event is fired.
await page.waitForNavigation({waitUntil: 'domcontentloaded'}); // consider navigation to be finished when the DOMContentLoaded event is fired.
await page.waitForNavigation({waitUntil: 'networkidle0'});     // consider navigation to be finished when there are no more than 0 network connections for at least 500 ms.
await page.waitForNavigation({waitUntil: 'networkidle2'});     // consider navigation to be finished when there are no more than 2 network connections for at least 500 ms.

Alternatively, you can use the waitUntil option in page.goto() to wait for the document to load:

await page.goto('https://example.com/', {waitUntil: 'load'});
await page.goto('https://example.com/', {waitUntil: 'domcontentloaded'});
await page.goto('https://example.com/', {waitUntil: 'networkidle0'});
await page.goto('https://example.com/', {waitUntil: 'networkidle2'});
like image 128
Grant Miller Avatar answered Oct 31 '22 13:10

Grant Miller


Sometimes waitForNavigation just timeout. I came up with other solution using the waitForFunction, checking if document is in ready state.

await page.waitForFunction(() => document.readyState === "complete");
like image 1
Yuri Olive Avatar answered Oct 31 '22 13:10

Yuri Olive