How to handle page navigation and redirection in Puppeteer?

To handle page navigation and redirection in Puppeteer, you can use the following methods:

  1. To navigate to a specific URL, you can use the page.goto() method. For example:
await page.goto('https://example.com');
  1. To navigate back, you can use the page.goBack() method. For example:
await page.goBack();
  1. To navigate forward, you can use the page.goForward() method. For example:
await page.goForward();
  1. To handle page redirection, you can listen for the response event and check the response status code. If the status code is a redirect (3xx), you can follow the redirect using the response.redirectChain() method. For example:
page.on('response', async (response) => { if (response.status() >= 300 && response.status() < 400) { const redirectChain = response.request().redirectChain(); if (redirectChain.length > 0) { const finalUrl = redirectChain[redirectChain.length - 1].url(); await page.goto(finalUrl); } } });

By using these methods and techniques, you can handle page navigation and redirection effectively in Puppeteer.