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:
-
Launch Puppeteer: Start Puppeteer and create a new page.
-
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. -
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.
-
Automation: Perform any actions or tests that rely on geolocation data, knowing that the browser will report the specified coordinates.
-
Headless Mode: If you prefer to run Puppeteer in headless mode (without a visible browser UI), remove the
{ headless: false }
option frompuppeteer.launch()
.