Playwright地理定位设置异常:指定经纬度无法生效
Playwright模拟地理定位失效问题
使用Playwright模拟指定经纬度(如纽约、伦敦、马德里等地)的地理定位时,输入的经纬度并未成功应用到页面/上下文,页面仍显示默认位置。已授予地理定位权限,但浏览器始终使用实际位置而非模拟位置。先后尝试通过test.use默认设置页面参数、在测试中手动为上下文设置定位,均无效。
测试代码
import { test, expect } from "@playwright/test"; test.use({ geolocation: { longitude: 41.890221, latitude: 12.492348 }, permissions: ['geolocation'], }); test("Change Locale Concept", async ({ page, context }) => { // Go to the location-checking website //await page.goto('https://mylocation.org/'); await context.setGeolocation({ longitude: 48.858455, latitude: 2.294474 }); await page.goto("https://www.bing.com/maps"); // Take a screenshot to verify settings await page.screenshot({ path: 'screenshot-us.png' }); // Inject a script to log the geolocation const geolocation = await page.evaluate(() => { return new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition( position => resolve(position.coords), error => reject(error) ); }); }); // Log the geolocation console.log(`Latitude: ${geolocation.latitude}, Longitude: ${geolocation.longitude}`); // Check the permissions of the page const permissions = await page.evaluate(async () => { const permissionNames = ['geolocation', 'notifications', 'camera', 'microphone']; const results = {}; for (const name of permissionNames) { try { const result = await navigator.permissions.query({ name }); results[name] = result.state; } catch (e) { results[name] = 'permission not available'; } } return results; }); // Log the permissions console.log('Permissions:', permissions); // Validate the geolocation permission expect(permissions.geolocation).toBe('granted'); });
测试输出
Latitude: undefined, Longitude: undefined Permissions: { geolocation: 'granted', notifications: 'denied', camera: 'denied', microphone: 'denied' }
可见地理定位权限已授予,但经纬度未按设置生效,输出的纬度和经度均为undefined。
解决方案
- 更新Playwright到最新版本:旧版本可能存在地理定位模拟的bug,执行
npm install @playwright/test@latest完成更新。 - 添加精度参数:调用
context.setGeolocation时补充accuracy参数,确保模拟定位的有效性:await context.setGeolocation({ longitude: 48.858455, latitude: 2.294474, accuracy: 100 }); - 捕获定位错误信息:修改
page.evaluate中的代码,捕获getCurrentPosition的错误,排查具体失败原因:const geolocation = await page.evaluate(() => { return new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition( position => resolve(position.coords), error => { console.error('定位错误:', error.message); reject(error); } ); }).catch(err => { console.log('捕获到错误:', err.message); return null; }); }); - 显式创建上下文:绕过
test.use的默认设置,手动创建上下文并配置定位参数,避免参数被覆盖:test("Change Locale Concept", async ({ browser }) => { const context = await browser.newContext({ geolocation: { longitude: 48.858455, latitude: 2.294474, accuracy: 100 }, permissions: ['geolocation'] }); const page = await context.newPage(); await page.goto("https://www.bing.com/maps"); // 后续测试逻辑... }); - 使用纯定位测试网站:部分网站(如Bing Maps)可能使用IP定位或自有服务,建议使用仅依赖浏览器
navigator.geolocation的测试网站验证模拟效果。
内容的提问来源于stack exchange,提问作者Ghumman
相关产品推荐
相关产品推荐

