0

I am trying to open a new tab in the browser. But however it open the second URL in the same tab.

Code:

import org.openqa.selenium.By; 
import org.openqa.selenium.Keys; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.chrome.ChromeDriver;

public class ChromeFlock {

    public static void main(String[] args) throws Exception {       WebDriver driver;       System.setProperty("webdriver.chrome.driver", "C:\\Automation\\chromedriver_win32\\chromedriver.exe");      driver = new ChromeDriver();
        driver.manage().window().maximize();

        String baseUrl = "http://www.google.co.uk/";
        driver.get(baseUrl);

        Thread.sleep(3000);

        String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t");
        driver.findElement(By.tagName("body")).sendKeys(selectLinkOpeninNewTab);

        driver.get("http://www.facebook.com");  }

}

3 Answers 3

1

use JavascriptExecutor as following:

((JavascriptExecutor) driver).executeScript("window.open('http://www.facebook.com');");
1

Perhaps you are not switching to the new tab, which is resulting in launching the 2nd link on the parent tab only.

You can use Robot class to open a new tab by simulating pressing of keyboard's Ctrl+t keys. Then you need to switch to the new tab using driver.switchTo() command.

For code snippet and details check this Open a new tab in Selenium

0

You could use keyboard emulation:

new Actions(driver).sendKeys(Keys.Control + 'w').build.perform(); // or + 't'
driver.get("http://www.facebook.com");

or using JavaScriptExecutor:

((JavascriptExecutor) driver).ExecuteScript("window.open('http://www.facebook.com','_blank');");
3
  • Still the same issue. Opens the second link the same tab and not the new one May 26, 2017 at 17:03
  • @ShaikhFarzan but have your previous tab finalize the loading? Try to increase timeouts
    – FieryCat
    May 26, 2017 at 19:10
  • @ShaikhFarzan, at least try to add .Build().Perform() to the end of your function driver.findElement(By.tagName("body")).sendKeys(selectLinkOpeninNewTab) to initialize a chain execution.
    – FieryCat
    May 26, 2017 at 19:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.