1

The part of the code which opens a new tab and opens a url in that new tab does not work. It opens the new tab but opens the new url in the previous tab itself. Can anyone help?

public class PractiseSession1 
{
public static void main(String[] args)

{
    // TODO Auto-generated method stub
    String URL="http://www.google.com";

    System.setProperty("webdriver.gecko.driver", "D:\\Sourav Mukherjee\\BP-Oyster\\S2\\Selenium Server\\geckodriver-v0.16.1-win64\\geckodriver.exe");
    DesiredCapabilities dc = DesiredCapabilities.firefox();
    dc.setCapability("marionette", true);
    WebDriver driver =  new FirefoxDriver(dc);
    driver.get(URL);

    //Open a url in a new tab
    driver.findElement(By.cssSelector("Body")).sendKeys(Keys.CONTROL+ "t");
    driver.get("http://facebook.com/");


}
}
ThugMeister22
  • 73
  • 1
  • 5
  • The focus is still on previous tab. Try to refresh the page. driver.manage().navigate().refresh(); – Ankur Jun 07 '17 at 10:01

2 Answers2

0

EDIT: The question isn't about moving to the new tab, but directly opening a link in the tab

You must move the driver to the new tab. To do this, you use this method:

ArrayList<String> tabs2 = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs2.get(1));
driver.close();
driver.switchTo().window(tabs2.get(0));
Turtle
  • 1,626
  • 16
  • 26
0

Here is the Answer to your Question:

To open an URL then again to open a second URL in another tab you can use JavascriptExecutor. Here is your own code which opens http://www.google.com in one tab and next opens http://facebook.com/ in another tab:

    String URL="http://www.google.com";
    System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
    DesiredCapabilities dc = DesiredCapabilities.firefox();
    dc.setCapability("marionette", true);
    WebDriver driver =  new FirefoxDriver(dc);
    driver.get(URL);
    ((JavascriptExecutor) driver).executeScript("window.open('http://facebook.com/');");

Let me know if this Answers your Question.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352