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.
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.
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.
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).
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'});
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With