Address.212, 2nd Floor, Grand Mall, Jalandhar, Punjab 144001, India

Tel. +91-7710795555

      +91-7710793555

QUICK LINKS

© 2019 by NTF. Proudly created with 9to5Technologies  privacy policy

Search
  • 9to5 Technologies

Open new link in a new tab or window and switch to it with Selenium WebDriver

Sometimes we need to open links in new Tab ow Window in selenium, here is the code for your help:

1. Open http://www.gmail.com 2. Open a new tab and switch to it 3. Open http://www.facebook.com in the new tab


Here is the solution for Chrome:

@Test

public void openNewTabInChrome() {

WebDriver driver = new ChromeDriver();

driver.get(“http://www.google.com”");

WebElement element = driver.findElement(By.linkText(“Gmail”));

Actions actionOpenLinkInNewTab = new Actions(driver);

actionOpenLinkInNewTab.moveToElement(element).keyDown(Keys.COMMAND).keyDown(Keys.SHIFT).click(element).keyUp(Keys.COMMAND).keyUp(Keys.SHIFT).perform();

ArrayList tabs = new ArrayList(driver.getWindowHandles()); driver.switchTo().window(tabs.get(1)); driver.get(“http://www.yahoo.com”");

driver.close(); driver.switchTo().window(tabs.get(0)); driver.get(“http: //www.facebook.com”);

driver.close();

}


Here is the solution for Firefox:


@Test

public void openNewTabInFirefox() {

WebDriver driver = new FirefoxDriver();

driver.get(“http: //www.google.com”");

WebElement body = driver.findElement(By.cssSelector(“body”));

String newTabAction = Keys.chord(Keys.COMMAND, “t”);

body.sendKeys(newTabAction);

String chooseTab = Keys.chord(Keys.COMMAND, “2”);

body.sendKeys(chooseTab);

}

0 views