Home  Puppeteer   How to simu ...

How to simulate geolocation in puppeteer

To simulate geolocation in Puppeteer, you can override the browser's geolocation settings using the setGeolocation method available on the Puppeteer page object. Here’s how you can simulate geolocation:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({ headless: false }); // Launch browser in non-headless mode for visibility
  const page = await browser.newPage();

  // Set the geolocation to a specific location
  await page.setGeolocation({ latitude: 37.7749, longitude: -122.4194 });

  // Navigate to a website that uses geolocation
  await page.goto('https://mygeolocationwebsite.com');

  // Continue with your automation...

  await browser.close();
})();

Explanation:

  1. Launch Puppeteer: Start Puppeteer and create a new page.

  2. Set Geolocation: Use page.setGeolocation() to specify the latitude and longitude of the location you want to simulate. For example, { latitude: 37.7749, longitude: -122.4194 } corresponds to San Francisco.

  3. Navigate to Website: Direct Puppeteer to navigate to a website that uses geolocation services. This could be any website where the geolocation functionality is enabled.

  4. Automation: Perform any actions or tests that rely on geolocation data, knowing that the browser will report the specified coordinates.

  5. Headless Mode: If you prefer to run Puppeteer in headless mode (without a visible browser UI), remove the { headless: false } option from puppeteer.launch().

Published on: Jun 28, 2024, 12:43 AM  
 

Comments

Add your comment