What is the Puppeteer equivalent of window.sessionStorage?
Alex K
alex k profile pic

To handle page redirects in Puppeteer, you can use thepage.waitForNavigation() method along with event listeners to detect and handle different types of redirects. Here's a detailed explanation of how to handle page redirects in Puppeteer: 1. Launching a new browser instance and creating a new page:

1
2
3
4
5
6
7
8
9
10
11
12
13

   const puppeteer = require('puppeteer');

   (async () => {
     const browser = await puppeteer.launch();
     const page = await browser.newPage();

     // Perform actions with the page here

     // Close the browser
     await browser.close();
   })();
   

This code sets up a basic Puppeteer script. It launches a new headless browser instance and creates a new page to work with. 2. Handling page redirects usingpage.waitForNavigation(): To handle page redirects, you can usepage.waitForNavigation() method to wait for the navigation to complete after a click or form submission. - Handling typical HTTP redirects:

1
2
3
4
5
6

     await Promise.all([
       page.waitForNavigation(), // Wait for the navigation to complete
       page.click('#redirectButton'), // Perform the action that triggers the redirect
     ]);
     

In this example,page.waitForNavigation() is used in conjunction withpage.click() to simulate a click on a button (#redirectButton in this case) that triggers the redirect. ThePromise.all() method is used to await both thewaitForNavigation() andclick() promises simultaneously. - Handling JavaScript-based redirects:

1
2
3
4
5
6
7
8
9
10
11
12

     page.on('framenavigated', async (frame) => {
       if (frame.url() === 'https://example.com/redirected') {
         // Redirect has occurred, handle it here
       }
     });

     await page.goto('https://example.com'); // Initial page load
     await page.evaluate(() => {
       window.location.href = 'https://example.com/redirected'; // JavaScript-based redirect
     });
     

In this example, an event listener ('framenavigated') is set up to detect when the frame navigation occurs. Inside the listener, theframe.url() is checked to determine if the redirected URL matches the expected URL ('https://example.com/redirected' in this case). If a match is found, you can handle the redirect accordingly.page.goto() is used to load the initial page, andpage.evaluate() is used to simulate a JavaScript-based redirect by changing thewindow.location.href. By implementingpage.waitForNavigation() and event listeners, you can handle different types of page redirects in Puppeteer. Whether it's an HTTP redirect or a JavaScript-based redirect, you can wait for the navigation to complete and perform the necessary actions accordingly. This functionality allows you to automate the handling of redirects during web scraping, form submissions, or any other scenario that involves interacting with pages that perform redirects.