1

I have a problem with Selenium 3 to open a new tab in Firefox and Chrome.

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

Doesn’t work in Chrome and Firefox.

I could use the following code for Chrome but not for Firefox, in Firefox it open new Windows.

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

I used currently:

  • selenium-server-standalone: 3.8.1

  • chromedriver: 2.34

  • geckodriver: 0.19.1

Many thanks in advance.

Bes Regards,

Salai

Community
  • 1
  • 1
zoram
  • 513
  • 2
  • 7
  • 18

3 Answers3

4

My solution, if anyone will need it in the future

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/')
1
  • To open a New Blank TAB in Firefox / Chrome / Internet Explorer you can use the following code block :

    ((JavascriptExecutor) driver).executeScript("window.open('','_blank');");
    
  • To open the URL http://localhost:8080/games.html#machine in a New TAB through Firefox / Chrome / Internet Explorer you can use the following code block :

    ((JavascriptExecutor) driver).executeScript("window.open('http://localhost:8080/games.html#machine');");
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
1

Use JavaScript to insert a link DOM node in current page, then click on it, remove it at last. DOM node should be supported by vary main browser.

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));
}

Please execute below javascript in your browser's DevTool Console Tab, if it worked as expect, above Java Code should also be worked.

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();
yong
  • 13,357
  • 1
  • 16
  • 27
  • this newTab() method open in firefox a new Windows. Not a tab. – zoram Jan 12 '18 at 13:48
  • I tried on my Firefox 57.0.4, it work fine. I updated my answer, please execute the javascript in my answer on your firefox firstly. – yong Jan 12 '18 at 13:58