You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium 4 Java中如何同时打开普通与无痕浏览器窗口

在Selenium 4 Java中同时打开普通模式与无痕模式窗口

问题原因

driver.switchTo().newWindow(WindowType.WINDOW) 是基于当前浏览器实例的配置创建新窗口,所以新窗口会继承原窗口的模式(普通模式)。要实现普通+无痕的组合,必须初始化两个独立的浏览器驱动实例,分别配置不同的启动参数。

解决方案代码示例

1. 启动普通模式窗口

// 初始化普通模式Chrome驱动
ChromeOptions normalOpts = new ChromeOptions();
WebDriver normalDriver = new ChromeDriver(normalOpts);
normalDriver.get("https://example.com");

2. 启动无痕模式窗口

// 初始化无痕模式Chrome驱动
ChromeOptions incognitoOpts = new ChromeOptions();
incognitoOpts.addArguments("--incognito"); // 添加上无痕启动参数
WebDriver incognitoDriver = new ChromeDriver(incognitoOpts);
incognitoDriver.get("https://example.com");

3. 多窗口操作示例(可选)

两个独立的驱动实例可以分别操作对应窗口:

// 获取普通窗口标题
String normalWindowTitle = normalDriver.getTitle();
// 获取无痕窗口标题
String incognitoWindowTitle = incognitoDriver.getTitle();

// 关闭所有窗口
normalDriver.quit();
incognitoDriver.quit();

其他浏览器无痕参数参考

  • Firefox:使用 --private 参数
  • Edge:使用 --inprivate 参数

内容的提问来源于stack exchange,提问作者Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 21:35:18