Vijayalaxmi Kummari
Vijayalaxmi Kummari

Reputation: 13

How to open a new tab in Chrome and switch to that new tab in Java using Selenium

This is the code that I have written to open a new tab in already opened in Chrome but it is redirecting to the second url in the existing tab only.

I want to open a new tab and load url of 'www.mailinator.com'

System.setProperty("webdriver.chrome.driver","D:\\Vijayalaxmi Testing\\BrowserDrivers\\ChromeDriver\\chromedriver.exe" );
    obj=new ChromeDriver();
    String baseUrl="https://www.google.co.in/";
    obj.get(baseUrl);

    obj.findElement(By.tagName("body")).sendKeys(Keys.CONTROL+"t");


    obj.get("https://www.mailinator.com/");

Can any one help me with this?

Upvotes: 1

Views: 1746

Answers (2)

user8507737
user8507737

Reputation:

use driver.switchTo().window(tabs.get(1)); to open new tab

obj=new ChromeDriver();
String baseUrl="https://www.google.co.in/";
obj.get(baseUrl);

obj.findElement(By.tagName("body")).sendKeys(Keys.CONTROL+"t");

ArrayList<String> tabs = new ArrayList<String> (obj.getWindowHandles());
driver.switchTo().window(tabs.get(1)); //switches to new tab

obj.get("https://www.mailinator.com/");

driver.switchTo().window(tabs.get(0)); // switch back to old

Upvotes: 0

Fenio
Fenio

Reputation: 3635

You can open new tab with javascript

public void openNewTab() {
    ((JavascriptExecutor)driver).executeScript("window.open('about:blank','_blank');");
}

If you want to perform operations within new tab you can use:

driver.switchTo().window(); This method accepts String as an argument. Window handle to be exact

You can get all handles like this

driver.getWindowHandles(). This will return you a Set of all handles in the current browser.

In order to switch to newly created tab, iterate through the handles and use switchTo() method like this:

    Set<String> handles = driver.getWindowHandles();
    String currentWindowHandle = driver.getWindowHandle();
    for (String handle : handles) {
        if (!currentWindowHandle.equals(handle)) {
            driver.switchTo().window(handle);
        }
    }

WARNING: This might be tricky if you have more than 2 tabs.

Upvotes: 1

Related Questions