元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
入门指南
Playwright安装与配置
环境要求与验证
第一个自动化测试脚本
▶
核心概念
Browser对象详解
Page对象操作指南
Frame与上下文管理
网络请求拦截与Mock
▶
元素定位与操作
CSS选择器实战
XPath高级定位技巧
文本定位与正则匹配
动态元素等待策略
▶
高级操作指南
文件上传下载处理
多标签页与弹窗管理
浏览器上下文隔离
设备模拟与地理定位
▶
测试框架集成
Jest集成配置
Mocha测试报告生成
持续集成CI/CD配置
▶
最佳实践
测试用例组织结构
性能优化策略
跨浏览器测试方案
▶
疑难解答
常见错误代码解析
元素定位失败分析
浏览器启动问题排查
▶
录制功能指南
录制功能基础入门
录制脚本生成与编辑
高级录制配置与技巧
录制脚本调试与优化
发布时间:
2025-03-27 19:15
↑
☰
# 浏览器上下文隔离 本文将详细介绍Playwright中的浏览器上下文隔离机制,帮助你理解如何管理独立的浏览器会话,实现测试环境的隔离。 ## 基本概念 ### 1. 浏览器上下文 ```typescript // 创建浏览器实例 const browser = await chromium.launch(); // 创建新的浏览器上下文 const context = await browser.newContext(); // 在上下文中创建页面 const page = await context.newPage(); // 关闭上下文 await context.close(); ``` ### 2. 上下文配置 ```typescript // 配置浏览器上下文 const context = await browser.newContext({ viewport: { width: 1280, height: 720 }, userAgent: 'Custom User Agent', locale: 'zh-CN', timezoneId: 'Asia/Shanghai' }); // 设置HTTP认证 const context = await browser.newContext({ httpCredentials: { username: 'admin', password: '123456' } }); ``` ## 隔离特性 ### 1. Cookie隔离 ```typescript // 在不同上下文中设置Cookie const context1 = await browser.newContext(); const context2 = await browser.newContext(); await context1.addCookies([{ name: 'session', value: 'user1', url: 'https://example.com' }]); await context2.addCookies([{ name: 'session', value: 'user2', url: 'https://example.com' }]); ``` ### 2. 存储隔离 ```typescript // localStorage隔离 const context1 = await browser.newContext(); const page1 = await context1.newPage(); await page1.evaluate(() => { localStorage.setItem('user', 'admin'); }); const context2 = await browser.newContext(); const page2 = await context2.newPage(); await page2.evaluate(() => { console.log(localStorage.getItem('user')); // null }); ``` ## 权限管理 ### 1. 基本权限 ```typescript // 设置地理位置权限 const context = await browser.newContext({ permissions: ['geolocation'] }); // 设置多个权限 const context = await browser.newContext({ permissions: ['notifications', 'camera', 'microphone'] }); // 动态更新权限 await context.grantPermissions(['clipboard-read']); ``` ### 2. 高级权限 ```typescript // 设置特定域名的权限 await context.grantPermissions(['geolocation'], { origin: 'https://example.com' }); // 清除权限 await context.clearPermissions(); ``` ## 网络隔离 ### 1. 请求拦截 ```typescript // 每个上下文独立的请求拦截 const context = await browser.newContext(); await context.route('**/api/**', route => { if (route.request().resourceType() === 'xhr') { route.fulfill({ status: 200, body: JSON.stringify({ data: 'mocked' }) }); } else { route.continue(); } }); ``` ### 2. 网络事件 ```typescript // 监听特定上下文的网络事件 context.on('request', request => { console.log(`${request.method()} ${request.url()}`); }); context.on('response', response => { console.log(`${response.status()} ${response.url()}`); }); ``` ## 最佳实践 ### 1. 上下文复用 ```typescript // 创建可重用的上下文配置 const contextOptions = { viewport: { width: 1280, height: 720 }, locale: 'zh-CN', permissions: ['geolocation'], httpCredentials: { username: 'admin', password: '123456' } }; // 创建多个相同配置的上下文 const context1 = await browser.newContext(contextOptions); const context2 = await browser.newContext(contextOptions); ``` ### 2. 状态持久化 ```typescript // 保存上下文状态 await context.storageState({ path: 'auth.json' }); // 使用保存的状态创建新上下文 const context = await browser.newContext({ storageState: 'auth.json' }); ``` ## 调试技巧 ### 1. 上下文调试 ```typescript // 启用上下文级别的调试 const context = await browser.newContext({ logger: { isEnabled: (name, severity) => severity === 'verbose', log: (name, severity, message) => console.log(`${name} ${message}`) } }); // 监控上下文事件 context.on('console', message => { console.log(`${message.type()}: ${message.text()}`); }); ``` ### 2. 错误处理 ```typescript // 捕获上下文级别的错误 context.on('pageerror', error => { console.error('页面错误:', error); }); context.on('requestfailed', request => { console.error('请求失败:', request.url()); }); ``` ## 常见问题 ### 1. 资源管理 ```typescript // 正确的资源清理 async function test() { const context = await browser.newContext(); try { const page = await context.newPage(); await page.goto('https://example.com'); // 执行测试 } finally { await context.close(); } } // 批量清理上下文 async function cleanup() { const contexts = browser.contexts(); await Promise.all(contexts.map(context => context.close())); } ``` ### 2. 性能优化 ```typescript // 限制上下文资源使用 const context = await browser.newContext({ viewport: { width: 1280, height: 720 }, deviceScaleFactor: 1, isMobile: false, hasTouch: false }); // 禁用不必要的功能 const context = await browser.newContext({ javascriptEnabled: true, offline: false, bypassCSP: false }); ``` ## 下一步 1. 了解[设备模拟与地理定位](/article/playwright/advanced/device-emulation) 2. 探索[Jest集成配置](/article/playwright/integration/jest) 3. 学习[Mocha测试报告生成](/article/playwright/integration/mocha) ## 参考资料 - [Playwright浏览器上下文](https://playwright.dev/docs/browser-contexts) - [Playwright隔离机制](https://playwright.dev/docs/isolation) - [Playwright权限管理](https://playwright.dev/docs/permissions)