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

使用Selenium3 WebDriver(Java)在Chrome和Firefox中打开新标签页求助

解决Selenium 3在Chrome/Firefox中打开新标签页的问题

我来帮你搞定这个新标签页的困扰~ 结合你用的Selenium和驱动版本,咱们一步步拆解问题、解决:

先纠正一个容易踩的小坑

你之前写的代码sendKeys(Keys.CONTROL +" ")里, 对应Tab键——这个快捷键是切换已有标签页的,不是打开新标签的!打开新标签的正确快捷键是Ctrl+T(Windows/Linux)或Cmd+T(Mac),这可能是你第一个方法无效的核心原因。


针对Chrome的稳定方案

你当前用的JS方法已经能在Chrome正常工作,另外也可以用Actions类模拟用户快捷键操作,更贴近真实交互:

// 先确保页面有焦点,点击body元素
SeleniumTestBase.getDriver().findElement(By.cssSelector("body")).click();
// 模拟Ctrl+T打开新标签
Actions actions = new Actions(SeleniumTestBase.getDriver());
actions.keyDown(Keys.CONTROL)
       .sendKeys("t")
       .keyUp(Keys.CONTROL)
       .perform();

针对Firefox的解决方案

你的JS方法在Firefox里开新窗口而非新标签,是因为旧版本geckodriver会遵循Firefox默认的_blank链接处理规则。这里给你两种可行方案:

方案1:配置FirefoxProfile强制_blank在新标签打开

通过修改Firefox的偏好设置,让所有_blank目标的链接/脚本都默认在新标签打开,这样你的JS代码就能正常工作:

// 创建FirefoxProfile并设置偏好
FirefoxProfile profile = new FirefoxProfile();
// 设置所有链接在当前窗口的新标签打开
profile.setPreference("browser.link.open_newwindow", 3);
// 取消对脚本打开窗口的限制
profile.setPreference("browser.link.open_newwindow.restriction", 0);
// 外部链接也强制在新标签打开(可选)
profile.setPreference("browser.link.open_newwindow.override.external", 3);

// 用配置好的profile初始化FirefoxDriver
WebDriver firefoxDriver = new FirefoxDriver(profile);

之后再执行你的JS代码:

JavascriptExecutor js = (JavascriptExecutor) firefoxDriver;
js.executeScript("window.open('http://localhost:8080/games.html#machine','_blank');");

就能在Firefox中打开新标签而不是新窗口了。

方案2:用Actions模拟快捷键打开新标签

和Chrome类似,通过Actions类模拟Ctrl+T快捷键(注意要先确保页面有焦点):

SeleniumTestBase.getDriver().findElement(By.cssSelector("body")).click();
Actions actions = new Actions(SeleniumTestBase.getDriver());
actions.keyDown(Keys.CONTROL)
       .sendKeys("t")
       .keyUp(Keys.CONTROL)
       .perform();

如果是Mac系统,把Keys.CONTROL换成Keys.COMMAND即可。


额外提示

你当前使用的Selenium和驱动版本都比较老旧(selenium-server-standalone 3.8.1、geckodriver 0.19.1),如果条件允许,升级到较新的版本(比如Selenium 3.141.59+、geckodriver 0.30.0+)会获得更好的兼容性,很多旧版本的小问题都会被官方修复。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:00:32