Selenium WebDriver tool do not have any built In API using which we can directly use to open new tab. Normally we are using CTRL + t Keys to open new tab In Browser and cltr + tab to switch between the tabs. We will use this in our selenium test case to open another tab inside a browser and switch to tab.
Check out the Example below in details to understand how to open a new tab, how to open particular url in the new tab, how to switch between two tabs and how to close the tabs.
import java.util.Iterator; import java.util.Set; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; public class BromiumTests { WebDriver driver; Utils util; @BeforeTest public void setUp() { System.setProperty("webdriver.chrome.driver", "C:\\Softwares\\chromedriver_win32\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @Test public void testOpenYoutube() { driver.get("https://www.youtube.com"); driver.get("https://www.youtube.com/watch?v=9NXEnGiOeUU"); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); } @Test public void testOpenGmail() { switchToNewTab(); driver.get("http://www.gmail.com"); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } public void openNewTab() { ((JavascriptExecutor) driver).executeScript("window.open('about:blank','_blank');"); } public void switchToNewTab() { openNewTab(); String subWindowHandler = null; Set<String> handles = driver.getWindowHandles(); Iterator<String> iterator = handles.iterator(); while (iterator.hasNext()) { subWindowHandler = iterator.next(); } driver.switchTo().window(subWindowHandler); } @AfterClass public void tearDown() { driver.quit(); } }






