π₯ 90% of Playwright engineers miss these permission hacks for geolocation testingβhereβs how to ace them in your next interview scenario.
π Problem Statement
Testing locationβbased or mediaβaccess features in web apps is hard because you canβt manually grant permissions each run. You need a reproducible, automated way to grant/deny geolocation, camera, or microphone permissions and optionally mock sensor data.
π‘ Solution & Code Walkthrough
Playwright lets you configure permissions at the browserContext level. Grant the permission and supply mock coordinates or device constraints directly when creating the context.
import { chromium, Browser, BrowserContext, Page } from '@playwright/test';
(async () => {
let browser: Browser;
let context: BrowserContext;
let page: Page;
try {
// Launch browser
browser = await chromium.launch();
// Create a context with geolocation granted and mocked coordinates
context = await browser.newContext({
permissions: ['geolocation'], // β
grant permission
geolocation: { latitude: 34.052235, longitude: -118.243683 }, // Los Angeles
});
page = await context.newPage();
await page.goto('https://maps.google.com');
// Example assertion: check map center uses mocked location
const mapCenter = await page.evaluate(() => {
const el = document.querySelector('.map-center');
return el?.textContent;
});
console.log('Map center:', mapCenter);
} finally {
await context?.close();
await browser?.close();
}
})();
For camera/microphone, replace permissions: ['camera'] (or microphone) and optionally set recordVideoSize or use page.evaluate to trigger getUserMedia.
π Key Takeaways
β’ Use browser.newContext({ permissions: ['geolocation'] }) to grant access.
β’ Provide mock coordinates via geolocation option for deterministic tests.
β Avoid hardβcoding credentials inside the contextβkeep them in test fixtures.
β
Store permission configs in a reusable testFixtures.ts for DRY code.
β Quick Summary Q&A
β’ Q: Do I need separate contexts for each permission?
A: Yesβeach context is isolated, preventing crossβtest bleed.
β’ Q: Can I deny a permission?
A: Yes, pass permissions: [] or permissions: ['geolocation'] with deny flag in older Playwright versions.
TAGS: playwright, javascript, testing, automation, browser-permissions
ββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββββββββββββββββββββββββββββ
π² π
πππ ππππππ πππ β πππ+ ππππ π&ππ¬
Practice real-world interview scenarios offline on the free QA Automation & SDET Prep app:
π€ ππ¨π¨π π₯π ππ₯ππ² (ππ§ππ«π¨π’π):
https://play.google.com/store/apps/details?id=com.app.seleniuminterviewquestions&referrer=utm_source%3Ddevto%26utm_medium%3Darticle%26utm_campaign%3Dselenium_20260930
π ππ©π© πππ¨π«π (π’ππ):
https://apps.apple.com/app/id6786760948?pt=128640464&ct=devto_selenium_20260930&mt=8
ββββββββββββββββββββββββββββββββββββββββ
Top comments (0)