如何使用Selenium3 WebDriver和Java打开新标签Chrome和Firefox?

时间:2018-01-12 10:40:16

标签: selenium selenium-chromedriver geckodriver chrome-web-driver iedriverserver

我遇到了Selenium 3在Firefox和Chrome中打开新标签的问题。

SeleniumTestBase.getDriver().findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");

在Chrome和Firefox中不起作用。

我可以将以下代码用于Chrome,但不能用于Firefox,在Firefox中它可以打开新的Windows。

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

我目前使用过:

  
      
  • selenium-server-standalone:3.8.1

  •   
  • chromedriver:2.34

  •   
  • geckodriver:0.19.1

  •   

非常感谢提前。

问候,

萨莱

3 个答案:

答案 0 :(得分:1)

  • 要在New Blank TAB / Firefox / Chrome中打开 Internet Explorer ,您可以使用以下代码块:

    ((JavascriptExecutor) driver).executeScript("window.open('','_blank');");
    
  • URL http://localhost:8080/games.html#machine / {{1}中打开New TAB Firefox } / Chrome您可以使用以下代码块:

    Internet Explorer

答案 1 :(得分:1)

使用JavaScript在当前页面中插入链接DOM节点,然后单击它,最后将其删除。不同的主浏览器应该支持DOM节点。

public newTab(String url) {
    String script = 
        "var d=document,a=d.createElement('a');" + 
        "a.target='_blank';a.href='%s';a.innerHTML='new tab';" + 
        "d.body.appendChild(a);" + 
        "a.click();a.parentNode.removeChild(a);";

    ((JavascriptExecutor) driver).executeScript(String.format(script, url));
}

请在浏览器的DevTool控制台选项卡中执行以下javascript,如果它按预期工作,则上面的Java代码也应该有效。

var d=document,a=d.createElement('a');a.target='_blank';a.href='https://angularjs.org/';a.innerHTML='new tab';d.body.appendChild(a);a.click();

答案 2 :(得分:1)

我的解决方案,如果将来有人需要的话

driver.get('https://google.com')
last_handle = driver.current_window_handle
driver.execute_script('window.open("https://google.com", "new window")')
driver.switch_to.window(last_handle)
driver.close()
for i in driver.window_handles:
    driver.switch_to.window(i)
driver.get('https://google.com.ua/')