What is the Puppeteer equivalent of window.location?
Benjamin C
benjamin c profile pic

The Puppeteer equivalent ofwindow.location is accessing thepage.url() property or usingpage.evaluate() to retrieve the current URL of the page. Here's a detailed explanation of how to get the page URL 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. Retrieving the page URL usingpage.url(): The simplest way to get the current URL of the page is by accessing thepage.url() property.

1
2
3
4

   const currentUrl = await page.url();
   console.log('Current URL:', currentUrl);
   

In this example,page.url() is called to retrieve the URL of the page. The value is assigned to thecurrentUrl variable, which can then be used or displayed as needed. 3. Retrieving the page URL usingpage.evaluate(): Alternatively, you can usepage.evaluate() to execute JavaScript code within the page context and retrieve the URL.

1
2
3
4

   const currentUrl = await page.evaluate(() => window.location.href);
   console.log('Current URL:', currentUrl);
   

In this code snippet,page.evaluate() is used to execute JavaScript code within the page context. The evaluated code retrieves the URL usingwindow.location.href. The returned value is assigned to thecurrentUrl variable and can be used or displayed as needed. By following these steps, you can access the current URL of the page in Puppeteer. Whether you usepage.url() to directly retrieve the URL orpage.evaluate() to execute JavaScript code within the page context, you can obtain the page URL for further processing or validation.