如何使用Playwright自动化Electron.WebContentsView?适配原BrowserWindow代码
Electron WebContentsView 下 Playwright 测试代码修改建议
当应用从BrowserWindow切换到WebContentsView后,原代码中electronApp.firstWindow()方法不再适用——该方法仅针对传统BrowserWindow实例。针对Playwright 1.56.0版本,可通过以下方式修改代码:
修改后的代码
const electronApp = await _electron.launch({ executablePath: path.resolve(localExePath), offline: false, }); // 获取所有Electron上下文,WebContentsView对应的页面会包含在上下文的pages集合中 const allPages = electronApp.contexts().flatMap(context => context.pages()); // 取第一个可用页面,若有多个WebContentsView可通过标题/URL筛选 pageFixture = allPages[0]; // 可选:通过页面标题筛选目标页面 // pageFixture = allPages.find(page => page.title() === "目标页面标题"); await pageFixture.waitForLoadState();
关键说明
electronApp.contexts()会返回应用内所有Electron上下文,WebContentsView的WebContents实例对应的页面会被包含在各上下文的pages()集合中- 若应用存在多个WebContentsView,建议通过页面标题、URL等唯一标识筛选目标页面,避免取错实例
- Playwright 1.56.0已原生支持Electron WebContentsView的页面获取,无需额外依赖或配置
内容的提问来源于stack exchange,提问作者Lalit
相关产品推荐
相关产品推荐

