Geolocation simulation in Playwright
To emulate geolocation in Playwright, you need to set the geolocation coordinates in the browser context options. You can specify the latitude, longitude, and accuracy of the geolocation.
Here’s how you can emulate geolocation in Playwright:
Example
Here's a script to set geolocation to a specific location (e.g., New York City) using Playwright:
const { chromium } = require('playwright');
(async () => {
// Launch the browser
const browser = await chromium.launch({ headless: false });
// Create a new browser context with geolocation
const context = await browser.newContext({
// Set geolocation options
geolocation: { latitude: 40.730610, longitude: -73.935242, accuracy: 100 },
// Set permissions for geolocation
permissions: ['geolocation']
});
// Create a new page
const page = await context.newPage();
// Navigate to a webpage that uses geolocation
await page.goto('https://www.google.com/maps');
// Wait for the page to load
await page.waitForLoadState('load');
// Perform actions or assertions on the page with geolocation
console.log('Geolocation set to New York City');
// Close the browser
await browser.close();
})();
Explanation
-
Launch the Browser:
const browser = await chromium.launch({ headless: false });
- This launches a Chromium browser. Setting
headless: false
will open the browser window so you can see the actions.
- This launches a Chromium browser. Setting
-
Create a New Browser Context with Geolocation:
const context = await browser.newContext({ geolocation: { latitude: 40.730610, longitude: -73.935242, accuracy: 100 }, permissions: ['geolocation'] });
geolocation
sets the desired latitude, longitude, and accuracy. In this example, it's set to New York City.permissions: ['geolocation']
grants the geolocation permission to the context.
-
Create a New Page:
const page = await context.newPage();
-
Navigate to a Webpage that Uses Geolocation:
await page.goto('https://www.google.com/maps');
-
Wait for the Page to Load:
await page.waitForLoadState('load');
-
Perform Actions or Assertions on the Page with Geolocation:
console.log('Geolocation set to New York City');
-
Close the Browser:
await browser.close();
Running the Script
Save the script to a file (e.g., geolocation_emulation.js
) and execute it using Node.js:
node geolocation_emulation.js
Published on: Jun 28, 2024, 03:26 AM