A Deep Dive into Geolocation with Playwright(TypeScript)
In today’s location-aware web landscape, testing your application’s behavior across different geographic locations is crucial. Whether it’s validating localized content, ensuring region-specific functionality, or simulating user experiences from various parts of the globe, controlling geolocation within your automated tests is essential.
This blog post dives into the world of geolocation manipulation using Playwright and TypeScript. We’ll explore how to set custom locations, understand the nuances of permission handling, and walk through practical examples to equip you with the tools for robust geolocation testing.
Setting the Stage: Playwright and Geolocation
Playwright, Microsoft’s powerful browser automation library, provides a streamlined approach to managing geolocation within your tests. Its intuitive API empowers you to seamlessly set coordinates, overriding the browser’s default location detection mechanism.
Let’s begin by outlining the fundamental steps involved:
- Installation: Ensure you have Playwright and TypeScript set up:
npm install --save-dev playwright @types/playwright
2. Add permission setting in playwright.config.ts
projects: [
// {
// name: 'chromium',
// use: { ...devices['Desktop Chrome'] },
// },
...
{
name: 'Google Chrome',
use: { ...devices['Desktop Chrome'], channel: 'chrome', screenshot: "only-on-failure", },
},
]
import { chromium } from 'playwright';
async function testGeolocation() {
const browser = await chromium.launch();
const page = await browser.newPage();
// Set desired geolocation coordinates
await page.setGeolocation({ latitude: 40.7128, longitude: -74.0060 });
await context.grantPermissions(['geolocation']);
// Navigate to a website using geolocation
await page.goto('https://www.google.com/maps');
// Add assertions or actions based on the set location
await browser.close();
}
testGeolocation();
- (If you haven’t already, download browsers using:
npx playwright install
) - Project Setup: Create a TypeScript file (e.g.,
geolocation.ts
) for your test script. - Basic Geolocation Setting:
In this example, we launch a Chromium browser instance, set the geolocation to Sawangan City using page.setGeolocation()
, and then navigate to Google Maps. This will center the map on the provided coordinates.
Permissions and Overriding
Modern web browsers prioritize user privacy and require explicit permission before sharing geolocation data with websites. Playwright allows us to elegantly handle these permission prompts:
- Granting Geolocation Permission:
// … (Your previous code)
const context = await browser.newContext({ geolocation: { latitude: 40.7128, longitude: -74.0060 }, permissions: ['geolocation'] });
const page = await context.newPage();
By setting permissions: ['geolocation']
within the browser context, we pre-authorize geolocation access for all pages within that context.
2. If you need to change geolocation settings during a test, you can modify them on-the-fly:
// ...
await context.grantPermissions(['geolocation'], { origin: 'https://www.google.com' });
// ...
This snippet grants geolocation permission specifically for the https://www.google.com
origin.
Practical Examples: Putting it All Together
Let’s explore some practical scenarios to solidify our understanding:
- Testing Region-Specific Functionality Manually:
import { test, expect } from '@playwright/test';
test('Verify Location on OpenWeatherMap', async ({ page, context }) => {
// Set the geolocation to Sawangan City
await page.context().setGeolocation({ latitude: -6.4240331, longitude: 106.7753368 });
await page.context().grantPermissions(['geolocation']);
// Navigate to OpenWeatherMap
await page.goto('https://openweathermap.org/');
// Get the location displayed on the page
const locationElement = await page.locator('.current-container.mobile-padding h2');
const displayedLocation = await locationElement.textContent();
// Assert that the displayed location includes "Sawangan"
expect(displayedLocation).toContain('Sawangan');
});
This example checks if an site correctly when the user’s location is set to Sawangan with latitude: -6.4240331 and longitude: 106.7753368.
2. Get Current Location Automatic by Script
Create file to make a function to get current location with name file is geolocation.ts. In this function the author tries to get geolocation data automatically through the provider https://ipinfo.io. It one of the trusted source for IP geolocation, company, carrier and IP type data sets.
const axios = require('axios');
async function getGeolocation() {
const response = await axios.get('https://ipinfo.io/json');
const [latitude, longitude] = response.data.loc.split(',').map(Number);
return { latitude, longitude };
}
module.exports = getGeolocation;
Then, add the following code to integrate the getGeolocation
function into your Playwright test
const getGeolocation = require('./geolocation');
test('Verify Location on OpenWeatherMap', async ({ page, context }) => {
// Set the geolocation to Sawangan City
const { latitude, longitude } = await getGeolocation();
await context.setGeolocation({ latitude, longitude }); await page.context().grantPermissions(['geolocation']);
await context.grantPermissions(['geolocation']);
// Navigate to OpenWeatherMap
await page.goto('https://openweathermap.org/');
// Get the location displayed on the page
const locationElement = await page.locator('.current-container.mobile-padding h2');
const displayedLocation = await locationElement.textContent();
// Assert that the displayed location includes "Sawangan"
expect(displayedLocation).toContain('Sawangan');
});
Conclusion
By following this tutorial, we can ensure that your web applications handle geolocation accurately. Effective geolocation testing is paramount in our location-aware digital world. Playwright, with its intuitive API and powerful features, provides test with the tools need to comprehensively test and ensure our applications behave as expected across diverse geographic locations.