How to open a new tab and new window in Selenium WebDriver with Java

You might have come across scenarios where you want to open a new browser tab or new browser window and perform some actions on newly opened tab or window.

We will look at how we can achieve the same using Selenium WebDriver.

  1. element.sendKeys(Keys.CONTROL,”t”);
  2. element.sendKeys(Keys.CONTROL + “t”);
  3. String chord = Keys.chord(Keys.CONTROL, “t”);
    element.sendKeys(chord);
  4. String  chord = Keys.chord(Keys.CONTROL + “t”);
    element.sendKeys(chord);

public class SendKeysAdvanced {

      public static void main(String[] args) throws Exception {

             WebDriver driver = new FirefoxDriver();
             driver.manage().window().maximize();
             driver.get(“http://www.seleniumlive.wordpress.com/”);

             WebElement elem = driver.findElement(By
.xpath(“//div[@id=’secondary’]//input[@class=’search-field’]”));

             // approach 1
             elem.sendKeys(Keys.CONTROL, “t”);

             // approach 2
            elem.sendKeys(Keys.CONTROL + “t”);

            // approach 3
            String chord = Keys.chord(Keys.CONTROL, “t”);
            elem.sendKeys(chord);

            // approach 4
            String chord = Keys.chord(Keys.CONTROL + “t”);
            elem.sendKeys(chord);

          }
}

To open a new window, we can use Keys.CONTROL + “n” (Ctrl+N) in the same manner.

To know more about Keys Enumeration visit the link.

Hope it helps you!

Cheers 🙂

Advertisements

#keys-enum, #new-tab-in-selenium, #new-window-in-selenium